<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/">
  <channel>
    <title>Core Java from First Principles | unkletayo.dev</title>
    <link>https://unkletayo.dev</link>
    <description>Learn Java without frameworks: how the language, JVM and standard library actually work, from source file to running program.</description>
    <language>en</language>
    <managingEditor>contact@unkletayo.dev (Adetayo Akinsanya)</managingEditor>
    <lastBuildDate>Tue, 10 Nov 2026 07:00:00 GMT</lastBuildDate>
    <atom:link href="https://unkletayo.dev/engineering/core-java/rss.xml" rel="self" type="application/rss+xml"/>
    <item>
      <title>Java NIO: channels, buffers, and serialization</title>
      <link>https://unkletayo.dev/engineering/core-java/24-channels-buffers-and-serialization/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/24-channels-buffers-and-serialization/</guid>
      <description>NIO channels as bidirectional I/O abstractions, ByteBuffer as a positioned memory region, FileChannel for large file reads and memory-mapped files, SelectableChannel and Selector for non-blocking I/O, and Java object serialization: the contract, the risks, and the alternatives.</description>
      <pubDate>Tue, 10 Nov 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>io</category>
      <category>nio</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/24-channels-buffers-and-serialization.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/24-channels-buffers-and-serialization.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/24-channels-buffers-and-serialization.png" alt="Java NIO: channels, buffers, and serialization" /></p>
<pre><code class="language-java">try (FileChannel channel = FileChannel.open(Path.of("data.bin"), StandardOpenOption.READ)) {
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        process(buffer);
        buffer.clear();
    }
}
</code></pre>
<p>This reads a file in 4096-byte chunks without loading the whole file into memory. The channel is not a stream: it's bidirectional, it works with buffers rather than individual bytes, and it can operate without blocking a thread. This part explains what that means and when it matters.</p>
<h2>What a channel is</h2>
<p>A <code>Channel</code> represents a connection to an I/O resource: a file, a socket, a pipe. Where a stream is directional (an <code>InputStream</code> reads, an <code>OutputStream</code> writes), a channel is typically bidirectional. <code>FileChannel</code> can read and write the same file. <code>SocketChannel</code> can read and write on the same connection.</p>
<p>Channels don't work with individual bytes. They work with <code>Buffer</code> objects — fixed-size memory regions that hold data to be read or written.</p>
<p>The core operations on a <code>ReadableByteChannel</code>:</p>
<pre><code class="language-java">int bytesRead = channel.read(buffer);  // fills buffer from the channel
</code></pre>
<p>And on <code>WritableByteChannel</code>:</p>
<pre><code class="language-java">int bytesWritten = channel.write(buffer);  // drains buffer to the channel
</code></pre>
<p>Both return the number of bytes transferred, or -1 at end of stream.</p>
<h2>ByteBuffer: a positioned memory region</h2>
<p><code>ByteBuffer</code> is the workhorse of NIO. It wraps a byte array with three tracked positions:</p>
<ul>
<li><strong>capacity</strong>: the total size of the underlying array — fixed at creation.</li>
<li><strong>limit</strong>: the boundary beyond which data should not be read or written — the "active" region.</li>
<li><strong>position</strong>: the current read/write cursor.</li>
</ul>
<p>When you create a buffer and write into it, position advances. When you switch from writing to reading, you call <code>flip()</code>. Flip sets <code>limit = position</code> and <code>position = 0</code>, so reading starts at the beginning and stops where writing stopped. When you're done reading and want to reuse the buffer, call <code>clear()</code>: it resets <code>position = 0</code> and <code>limit = capacity</code>.</p>
<pre><code class="language-java">ByteBuffer buffer = ByteBuffer.allocate(8);
// capacity=8, limit=8, position=0

buffer.put((byte) 65);  // writes 'A'
buffer.put((byte) 66);  // writes 'B'
// position=2

buffer.flip();
// limit=2, position=0

buffer.get();  // returns 65 ('A'), position=1
buffer.get();  // returns 66 ('B'), position=2

buffer.clear();
// limit=8, position=0 — ready to write again
</code></pre>
<p>The flip/clear pattern is the main source of bugs with ByteBuffer. Forgetting <code>flip()</code> before reading means you read from position onward (which is the end of the written data), and you get garbage or nothing.</p>
<h2>Reading a file with FileChannel</h2>
<p><code>FileChannel.open</code> opens a file channel with the specified options. Reading is the same read-flip-clear loop from the opening example:</p>
<pre><code class="language-java">try (FileChannel channel = FileChannel.open(
        Path.of("data.bin"), StandardOpenOption.READ)) {
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        while (buffer.hasRemaining()) {
            byte b = buffer.get();
            process(b);
        }
        buffer.clear();
    }
}
</code></pre>
<p><code>buffer.hasRemaining()</code> returns <code>position &lt; limit</code>, so the inner loop drains the buffer completely before the outer loop fills it again.</p>
<p>For most file reading, <code>Files.readAllBytes</code> or <code>Files.newBufferedReader</code> from the previous part are simpler. <code>FileChannel</code> earns its verbosity when you need random access, memory mapping, or file locking.</p>
<h2>Random access</h2>
<p><code>FileChannel</code> has a <code>position(long)</code> method that seeks to a byte offset within the file — something streams cannot do:</p>
<pre><code class="language-java">try (FileChannel channel = FileChannel.open(
        Path.of("index.bin"), StandardOpenOption.READ)) {
    channel.position(1024);  // seek to byte 1024
    ByteBuffer buffer = ByteBuffer.allocate(16);
    channel.read(buffer);
    buffer.flip();
    // read the 16 bytes starting at offset 1024
}
</code></pre>
<p><code>channel.size()</code> returns the current file size in bytes.</p>
<h2>Memory-mapped files</h2>
<p>For very large files that need frequent random reads, <code>FileChannel.map</code> maps a region of the file directly into the process's virtual address space:</p>
<pre><code class="language-java">try (FileChannel channel = FileChannel.open(
        Path.of("large.bin"), StandardOpenOption.READ)) {
    MappedByteBuffer mapped = channel.map(
        FileChannel.MapMode.READ_ONLY, 0, channel.size());
    // mapped behaves like a ByteBuffer backed by the file
    byte first = mapped.get(0);
    byte last  = mapped.get((int) channel.size() - 1);
}
</code></pre>
<p>The OS handles paging: only the pages actually accessed are loaded from disk. For read-mostly workloads on large data files (logs, databases, indices), this can be faster than read loops because it avoids copying data through a kernel buffer into a Java byte array.</p>
<p>The <code>MappedByteBuffer</code> survives the channel being closed. The underlying mapping lives until the buffer is garbage collected, though the JVM does not guarantee when that happens.</p>
<h2>Non-blocking I/O and Selector</h2>
<p>For network servers, the blocking model — one thread per connection, each thread blocking on reads and writes — becomes expensive when connection counts reach thousands. NIO addresses this with non-blocking channels and <code>Selector</code>.</p>
<p>A <code>SocketChannel</code> can be switched to non-blocking mode:</p>
<pre><code class="language-java">SocketChannel client = SocketChannel.open();
client.configureBlocking(false);
</code></pre>
<p>In non-blocking mode, <code>channel.read(buffer)</code> returns immediately: it transfers whatever bytes are available right now, which may be zero. The caller must check and retry rather than wait.</p>
<p><code>Selector</code> multiplexes many non-blocking channels onto one thread. You register channels with the selector and specify which events you care about (<code>OP_READ</code>, <code>OP_WRITE</code>, <code>OP_ACCEPT</code>, <code>OP_CONNECT</code>). Then <code>selector.select()</code> blocks until at least one channel is ready:</p>
<pre><code class="language-java">Selector selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ);

while (true) {
    selector.select();  // blocks until something is readable
    Set&lt;SelectionKey&gt; ready = selector.selectedKeys();
    for (SelectionKey key : ready) {
        if (key.isReadable()) {
            SocketChannel ch = (SocketChannel) key.channel();
            ch.read(buffer);
            // handle data
        }
    }
    ready.clear();
}
</code></pre>
<p>This is the reactor pattern: one thread drives many connections. For most Java server applications you won't write this directly — Netty, Vert.x, and Java's own <code>java.net.http.HttpClient</code> handle NIO internally. But knowing the model explains why those frameworks can serve ten thousand concurrent connections with a handful of threads.</p>
<h2>Java object serialization</h2>
<p><code>Serializable</code> is a marker interface. A class that implements it is telling the JVM: "you may convert instances of this class to a byte stream and reconstruct them later." This is Java's built-in object serialization.</p>
<pre><code class="language-java">class Account implements Serializable {
    String owner;
    double balance;
}

// writing:
try (ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("account.ser"))) {
    out.writeObject(new Account("Adetayo", 5000));
}

// reading:
try (ObjectInputStream in = new ObjectInputStream(
        new FileInputStream("account.ser"))) {
    Account account = (Account) in.readObject();
}
</code></pre>
<p>The mechanism works. The problems are severe enough that it appears on most "do not use in new code" lists today.</p>
<p><strong>What can go wrong.</strong> <code>readObject()</code> throws <code>ClassNotFoundException</code> if the class structure has changed in a way the serialization stream doesn't match. It can also execute arbitrary code: gadget chains in the deserialized object graph can trigger actions during reconstruction. The JVM itself loaded classes and ran constructors for every object in the stream, based entirely on data you just read from an untrusted source. This is why Java deserialization vulnerabilities appear repeatedly in security advisories.</p>
<p>The serialization stream also creates a tight coupling between the class and its serialized form. Add a field, rename a field, change a type — the existing saved data may no longer load.</p>
<p><strong>Use <code>serialVersionUID</code> if you must keep it.</strong> When a class has no explicit <code>serialVersionUID</code>, the JVM computes one from the class structure. Any change to the class changes the computed ID, which makes old data unloadable with an <code>InvalidClassException</code>. Declaring a fixed <code>serialVersionUID</code> suppresses that check; it moves the problem from "fails at load time" to "silently loads corrupted data."</p>
<p><strong>What to use instead.</strong> For persistence and interchange, JSON (Jackson, Gson) and Protocol Buffers produce formats that are independent of Java class identity. They're readable, versionable, and language-agnostic. For caching and sessions, the same applies. If you need a Java-only binary format that's safe and fast, look at Kryo or MessagePack with explicit schema versioning. Avoid <code>ObjectInputStream</code> for data from external or untrusted sources.</p>
<p>JEP 290 (Java 9) introduced serialization filters that let you whitelist or size-limit what <code>ObjectInputStream</code> will reconstruct. It reduced the attack surface but didn't change the fundamental coupling problem.</p>
<h2>Resource lifetime</h2>
<p>Every <code>InputStream</code>, <code>OutputStream</code>, <code>Reader</code>, <code>Writer</code>, <code>Channel</code>, <code>Selector</code>, and <code>Stream&lt;Path&gt;</code> holds an OS resource: a file descriptor, a socket descriptor, or a directory iterator. If you don't close them, the JVM eventually finalizes them, but finalizers are unreliable in timing. On systems with tight file descriptor limits, leaked descriptors cause <code>java.io.IOException: Too many open files</code>.</p>
<p><code>try</code>-with-resources handles this. Any class that implements <code>Closeable</code> can appear in the resource declaration:</p>
<pre><code class="language-java">try (InputStream a = ...; InputStream b = ...) {
    // both a and b are closed when this block exits, even on exception
}
</code></pre>
<p>Resources are closed in reverse declaration order. If closing <code>a</code> throws and closing <code>b</code> also throws, the second exception is suppressed (attached to the first with <code>addSuppressed</code>).</p>
<p>The rule: if you open it, close it. If you're unsure whether a stream was opened successfully, use <code>try</code>-with-resources and let the language handle the cleanup.</p>
]]></content:encoded>
    </item>
    <item>
      <title>How Java navigates the filesystem: files, paths, and I/O</title>
      <link>https://unkletayo.dev/engineering/core-java/23-files-and-paths/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/23-files-and-paths/</guid>
      <description>Path as a filesystem location description, Path.of and path operations, Files utility methods for reading and writing text and bytes, file metadata, creating and deleting, copying and moving, listing and walking directories, and what changed from the java.io.File API.</description>
      <pubDate>Tue, 03 Nov 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>io</category>
      <category>nio2</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/23-files-and-paths.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/23-files-and-paths.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/23-files-and-paths.png" alt="How Java navigates the filesystem: files, paths, and I/O" /></p>
<pre><code class="language-java">Path config = Path.of("config/settings.json");
System.out.println(Files.exists(config));
</code></pre>
<p><code>config</code> is a path — a description of a location in the filesystem hierarchy. Creating it doesn't open a file, acquire a lock, or verify that anything is on disk. <code>Files.exists</code> is the first contact with the actual filesystem. This distinction is what makes the NIO.2 API in <code>java.nio.file</code> easier to reason about than the older <code>java.io.File</code>.</p>
<h2>What a Path represents</h2>
<p>A <code>Path</code> is a sequence of name elements separated by the platform's path separator. On Unix it's <code>/</code>; on Windows it's <code>\</code>. <code>Path.of("config/settings.json")</code> has two elements: <code>config</code> and <code>settings.json</code>. <code>Path.of("/etc/hosts")</code> has two elements under the root <code>/</code>.</p>
<p><code>Path.of()</code> was added in Java 11. Before that, the equivalent was <code>Paths.get()</code> (available since Java 7). They return the same thing; <code>Path.of</code> just moved the factory into the interface itself.</p>
<p>A path can be absolute or relative. <code>Path.of("/etc/hosts")</code> is absolute: it starts from the filesystem root. <code>Path.of("config/settings.json")</code> is relative: it means "relative to whatever the current working directory turns out to be."</p>
<p>A few operations that work on the path string alone, without touching the disk:</p>
<pre><code class="language-java">Path p = Path.of("/var/log/app/errors.log");

p.getFileName();   // errors.log
p.getParent();     // /var/log/app
p.getRoot();       // /

p.getName(0);      // var  (first element after root)
p.getNameCount();  // 4    (var, log, app, errors.log)
</code></pre>
<p><code>resolve()</code> appends a path to another:</p>
<pre><code class="language-java">Path base = Path.of("/var/log");
Path full = base.resolve("app/errors.log");
// full is /var/log/app/errors.log
</code></pre>
<p>If the argument to <code>resolve</code> is absolute, it replaces the base entirely: <code>base.resolve("/etc/hosts")</code> returns <code>/etc/hosts</code>. That's by design — it makes it safe to pass either a relative or absolute path without special-casing.</p>
<p><code>normalize()</code> removes <code>.</code> and <code>..</code> components. <code>Path.of("/var/log/../log/app/./errors.log").normalize()</code> returns <code>/var/log/app/errors.log</code>.</p>
<h2>Reading files</h2>
<p><code>Files.readString</code> (Java 11+) reads an entire file into a <code>String</code>:</p>
<pre><code class="language-java">String content = Files.readString(Path.of("message.txt"), StandardCharsets.UTF_8);
</code></pre>
<p><code>Files.readAllBytes</code> does the same without decoding:</p>
<pre><code class="language-java">byte[] raw = Files.readAllBytes(Path.of("image.png"));
</code></pre>
<p>Both load the whole file at once. For small files — configs, templates, test data — that's fine. For large files, read line by line instead:</p>
<pre><code class="language-java">try (BufferedReader reader = Files.newBufferedReader(
        Path.of("large.csv"), StandardCharsets.UTF_8)) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}
</code></pre>
<p><code>Files.lines</code> (Java 8+) wraps the same reader in a <code>Stream&lt;String&gt;</code>, which lets you use stream operations on the lines:</p>
<pre><code class="language-java">try (Stream&lt;String&gt; lines = Files.lines(Path.of("large.csv"), StandardCharsets.UTF_8)) {
    long count = lines.filter(l -&gt; l.startsWith("ERROR")).count();
}
</code></pre>
<p>The <code>try</code>-with-resources is not optional here. <code>Files.lines</code> returns a stream backed by an open reader; closing the stream closes the reader. If you forget the <code>try</code> block, you leak a file descriptor.</p>
<h2>Writing files</h2>
<p><code>Files.writeString</code> (Java 11+) writes a <code>String</code> to a file, creating it if it doesn't exist:</p>
<pre><code class="language-java">Files.writeString(Path.of("output.txt"), content, StandardCharsets.UTF_8);
</code></pre>
<p>By default it truncates the file. To append instead:</p>
<pre><code class="language-java">Files.writeString(
    Path.of("log.txt"),
    "new entry\n",
    StandardCharsets.UTF_8,
    StandardOpenOption.CREATE,
    StandardOpenOption.APPEND
);
</code></pre>
<p><code>CREATE</code> creates the file if absent; without it, the write fails on a missing file. <code>APPEND</code> positions the write at the end of the existing content.</p>
<p>For raw bytes, <code>Files.write</code>:</p>
<pre><code class="language-java">Files.write(Path.of("data.bin"), bytes);
</code></pre>
<p>It accepts the same <code>StandardOpenOption</code> varargs.</p>
<p>For large text output, <code>Files.newBufferedWriter</code> avoids holding the entire string in memory:</p>
<pre><code class="language-java">try (BufferedWriter writer = Files.newBufferedWriter(
        Path.of("report.txt"), StandardCharsets.UTF_8)) {
    for (String line : lines) {
        writer.write(line);
        writer.newLine();
    }
}
</code></pre>
<h2>Metadata</h2>
<p><code>Files</code> has a set of methods that read file attributes without opening the file for content:</p>
<pre><code class="language-java">Path p = Path.of("data.csv");

Files.exists(p);              // true if the path names an existing file or directory
Files.isRegularFile(p);       // true if it's a regular file (not a directory, symlink, etc.)
Files.isDirectory(p);         // true if it's a directory
Files.size(p);                // length in bytes; throws if the file doesn't exist
Files.getLastModifiedTime(p); // returns a FileTime
</code></pre>
<p>What about symbolic links? <code>Files.exists</code> follows symlinks by default: it returns <code>true</code> if the target exists. Pass <code>LinkOption.NOFOLLOW_LINKS</code> to check whether the symlink itself exists regardless of its target.</p>
<h2>Creating and deleting</h2>
<pre><code class="language-java">Files.createDirectory(Path.of("output"));
// throws FileAlreadyExistsException if it exists
// throws NoSuchFileException if the parent doesn't exist

Files.createDirectories(Path.of("output/reports/2026"));
// creates all missing components; does not throw if the path already exists
</code></pre>
<p><code>Files.delete</code> throws <code>NoSuchFileException</code> if the target doesn't exist. <code>Files.deleteIfExists</code> does the same but returns <code>false</code> instead of throwing when nothing was there:</p>
<pre><code class="language-java">Files.delete(Path.of("temp.bin"));          // throws if absent
Files.deleteIfExists(Path.of("temp.bin"));  // returns false if absent
</code></pre>
<p>You can't delete a non-empty directory with either method. Use <code>Files.walk</code> to traverse and delete contents first (see below), or a recursive helper.</p>
<h2>Copying and moving</h2>
<pre><code class="language-java">Files.copy(source, target);
// throws FileAlreadyExistsException if target exists

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
// overwrites target if it exists

Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
// on the same filesystem, move is typically atomic
</code></pre>
<p><code>Files.copy</code> can also copy from an <code>InputStream</code> into a file, or from a file into an <code>OutputStream</code>. That's useful when the source isn't a local file:</p>
<pre><code class="language-java">try (InputStream in = url.openStream()) {
    Files.copy(in, Path.of("downloaded.zip"), StandardCopyOption.REPLACE_EXISTING);
}
</code></pre>
<h2>Listing and walking directories</h2>
<p><code>Files.list</code> returns a <code>Stream&lt;Path&gt;</code> of the direct children of a directory — one level only, like <code>ls</code>:</p>
<pre><code class="language-java">try (Stream&lt;Path&gt; entries = Files.list(Path.of("/var/log"))) {
    entries.filter(Files::isRegularFile).forEach(System.out::println);
}
</code></pre>
<p><code>Files.walk</code> descends into subdirectories:</p>
<pre><code class="language-java">try (Stream&lt;Path&gt; all = Files.walk(Path.of("/var/log"))) {
    all.filter(p -&gt; p.toString().endsWith(".log"))
       .forEach(System.out::println);
}
</code></pre>
<p>Both return lazy streams backed by directory iterators; close them to release the underlying resources. The stream from <code>Files.walk</code> visits the starting directory itself first, then its children in depth-first order.</p>
<p>An optional depth argument limits how far <code>walk</code> descends: <code>Files.walk(start, 2)</code> visits the start, its children, and their children, then stops.</p>
<h2>Why not java.io.File</h2>
<p>Java has had a <code>java.io.File</code> class since version 1.0. You'll encounter it in older code. Its problems:</p>
<p><code>File.delete()</code> returns a <code>boolean</code>. If deletion fails, you don't know why — no exception, no message. <code>Files.delete(Path)</code> throws an exception with a reason.</p>
<p><code>File.list()</code> returns <code>null</code> on error (I/O failure, path not a directory). Every call site must null-check. <code>Files.list(Path)</code> throws <code>IOException</code>.</p>
<p><code>File</code> has no charset support. Reading a file through <code>new FileReader(file)</code> uses the platform default. <code>Files</code> takes charsets explicitly.</p>
<p>Convert a <code>File</code> to a <code>Path</code> with <code>file.toPath()</code>. Convert back with <code>path.toFile()</code>. The two types coexist; NIO.2 didn't remove the old API.</p>
<h2>Exercise</h2>
<p>Write a method that lists all files under a given directory with a <code>.java</code> extension, returning them sorted by file size (smallest first):</p>
<pre><code class="language-java">List&lt;Path&gt; javaFilesBySize(Path root) throws IOException
</code></pre>
<p>What do you use? <code>Files.walk</code>, <code>filter</code>, <code>sorted</code> with a comparator on <code>Files.size</code>, and <code>toList()</code>. What happens if one of the files is deleted between the walk and the size read?</p>
<p><code>Files.size</code> throws <code>NoSuchFileException</code> if the file no longer exists. A concurrent delete between listing and sizing is an IOException inside a stream operation. The safe approach is to catch it inside the comparator, treat the missing file as size zero or skip it, or use <code>Files.readAttributes</code> to read size and existence atomically from one <code>BasicFileAttributes</code> read per path.</p>
]]></content:encoded>
    </item>
    <item>
      <title>How Java reads and writes text: bytes, characters, and encoding</title>
      <link>https://unkletayo.dev/engineering/core-java/22-bytes-characters-and-encoding/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/22-bytes-characters-and-encoding/</guid>
      <description>The InputStream and OutputStream byte contracts, the Reader and Writer character contracts, charset encoding and decoding, the FileReader platform-default charset trap, Java 18&apos;s switch to UTF-8 as the standard default, buffering, and Files.readString for small files.</description>
      <pubDate>Tue, 27 Oct 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>io</category>
      <category>encoding</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/22-bytes-characters-and-encoding.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/22-bytes-characters-and-encoding.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/22-bytes-characters-and-encoding.png" alt="How Java reads and writes text: bytes, characters, and encoding" /></p>
<pre><code class="language-java">byte[] bytes = {79, 108, -61, -95};
System.out.println(new String(bytes));
</code></pre>
<p>What does this print? On a machine where the platform default charset is UTF-8, it prints <code>Olá</code>. On a machine with ISO-8859-1 as the default, it prints <code>OlÃ¡</code>. Same four bytes, two different strings. That's the encoding problem in one example, and it's what this part is about.</p>
<h2>InputStream: the byte contract</h2>
<p><code>InputStream</code> represents a source of bytes. The core method is:</p>
<pre><code class="language-java">public abstract int read() throws IOException;
</code></pre>
<p>It returns a single byte as an <code>int</code> in the range 0 to 255, or <code>-1</code> when the stream is exhausted.</p>
<p>Why <code>int</code> and not <code>byte</code>? A Java <code>byte</code> is signed, so its range is -128 to 127. The value 255, a perfectly valid byte, would be -1 when stored in a <code>byte</code> variable — the same value as the end-of-stream sentinel. Using <code>int</code> avoids that collision: data bytes come back as 0–255, and -1 is unambiguous.</p>
<p>Reading from a file one byte at a time:</p>
<pre><code class="language-java">try (InputStream in = new FileInputStream("data.bin")) {
    int b;
    while ((b = in.read()) != -1) {
        process(b);  // b is 0–255
    }
}
</code></pre>
<p>This is the right tool for binary files: images, compressed data, raw network bytes. For text, there's a better abstraction.</p>
<h2>Reader: the character contract</h2>
<p><code>Reader</code> represents a source of characters. Its core method mirrors <code>InputStream</code>:</p>
<pre><code class="language-java">public int read() throws IOException;
</code></pre>
<p>It returns a character as an <code>int</code> in the range 0 to 65535 (the Unicode Basic Multilingual Plane), or <code>-1</code> at end of stream. The same <code>int</code> trick applies: a Java <code>char</code> is unsigned and covers 0–65535, so -1 is an unambiguous sentinel.</p>
<p>Reading text:</p>
<pre><code class="language-java">try (Reader reader = new FileReader("message.txt")) {
    int ch;
    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);
    }
}
</code></pre>
<p>This reads characters. But there is a problem hidden in <code>new FileReader("message.txt")</code> — we'll get there in a moment.</p>
<h2>What encoding is</h2>
<p>A charset maps byte sequences to characters. UTF-8 encodes the character 'O' (U+004F) as the single byte <code>0x4F</code>. It encodes 'á' (U+00E1) as two bytes: <code>0xC3 0xA1</code>. ISO-8859-1 encodes 'á' as the single byte <code>0xE1</code>.</p>
<p>Back to the opening example. The four bytes <code>{79, 108, -61, -95}</code> are, in hex, <code>{4F, 6C, C3, A1}</code>. In UTF-8, <code>C3 A1</code> is the two-byte sequence for 'á', so the four bytes decode to <code>Olá</code>. In ISO-8859-1, <code>C3</code> decodes to 'Ã' and <code>A1</code> decodes to '¡', giving <code>OlÃ¡</code>.</p>
<p>The bytes didn't change. The interpretation did.</p>
<p>This is why <code>new String(bytes)</code> is unreliable. It calls <code>new String(bytes, Charset.defaultCharset())</code>, which depends on whatever charset the JVM was started with.</p>
<h2>InputStreamReader: explicit charset</h2>
<p><code>InputStreamReader</code> wraps an <code>InputStream</code> and decodes its bytes into characters using a named charset:</p>
<pre><code class="language-java">try (InputStream in = new FileInputStream("message.txt");
     Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
    int ch;
    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);
    }
}
</code></pre>
<p><code>StandardCharsets.UTF_8</code> is a constant in <code>java.nio.charset.StandardCharsets</code>, available since Java 7. The class holds constants for UTF-8, UTF-16, ISO-8859-1, US-ASCII, and two UTF-16 variants. For modern files and network data, UTF-8 is almost always the right choice.</p>
<p>What <code>InputStreamReader</code> does internally: it reads bytes from the underlying <code>InputStream</code> and groups them according to the charset's rules. For UTF-8, it reads multi-byte sequences and produces one char per decoded code point (or two chars for characters outside the BMP, as a surrogate pair). For ISO-8859-1, it treats every byte as one character.</p>
<h2>The FileReader default charset</h2>
<p><code>FileReader</code> is a convenience class that wraps <code>FileInputStream</code> with an <code>InputStreamReader</code>. Before Java 11, its only constructor took a file name or a <code>File</code>:</p>
<pre><code class="language-java">// Java 1.1 to Java 10: no way to specify charset
Reader reader = new FileReader("message.txt");  // uses Charset.defaultCharset()
</code></pre>
<p>The platform default was set by the OS locale. On Linux and macOS with a UTF-8 locale it was UTF-8. On Windows it was typically Windows-1252 for Western European locales. Code that worked on one machine could silently produce wrong results on another.</p>
<p>Java 11 added a charset-accepting constructor:</p>
<pre><code class="language-java">// Java 11+
Reader reader = new FileReader("message.txt", StandardCharsets.UTF_8);
</code></pre>
<p>Use this form. The overload without a charset exists for backward compatibility, not convenience.</p>
<h2>Java 18 changed the default</h2>
<p>JEP 400, shipped in Java 18, made UTF-8 the default charset on all platforms. Before Java 18, <code>Charset.defaultCharset()</code> returned whatever the OS locale specified. From Java 18 it returns UTF-8 regardless of the platform, unless you override it with a system property at startup.</p>
<p>What changes for existing code? Code that called <code>new FileReader(file)</code> and expected the platform locale's charset for correct decoding now decodes as UTF-8. If the files actually contain UTF-8, the behavior is the same. If they contain Windows-1252 or ISO-8859-1 and the code relied on the system default, it now produces wrong output.</p>
<p>Explicit charset arguments are unaffected by this change. That's another reason to prefer them.</p>
<h2>OutputStream and Writer</h2>
<p>The write side is symmetric. <code>OutputStream.write(int b)</code> writes one byte (the low 8 bits of the int). <code>Writer.write(int c)</code> writes one character. <code>OutputStreamWriter</code> connects the two, encoding chars to bytes using a specified charset:</p>
<pre><code class="language-java">try (OutputStream out = new FileOutputStream("output.txt");
     Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
    writer.write("Olá");
}
</code></pre>
<p><code>writer.write("Olá")</code> encodes the three Unicode characters to four UTF-8 bytes and passes them to the underlying <code>OutputStream</code>.</p>
<p><code>FileWriter</code> is the write-side equivalent of <code>FileReader</code>, with the same default-charset problem and the same Java 11 fix:</p>
<pre><code class="language-java">// Java 11+
Writer writer = new FileWriter("output.txt", StandardCharsets.UTF_8);
</code></pre>
<h2>Buffering</h2>
<p>Each call to <code>InputStream.read()</code> or <code>Writer.write(char)</code> goes to the OS. For a file, that's a system call per byte. Reading a 1 MB text file one byte at a time means roughly a million system calls; it's slow regardless of disk speed.</p>
<p><code>BufferedInputStream</code> and <code>BufferedReader</code> solve this by reading a block of bytes from the OS per request and holding the extras in memory. The default buffer size for both is 8192 bytes in OpenJDK.</p>
<p>For reading text with explicit charset and line-by-line access, the layers stack like this:</p>
<pre><code class="language-java">try (BufferedReader reader = new BufferedReader(
        new InputStreamReader(
            new FileInputStream("message.txt"),
            StandardCharsets.UTF_8))) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}
</code></pre>
<p><code>BufferedReader.readLine()</code> returns one line at a time, stripping the line terminator (<code>\n</code>, <code>\r\n</code>, or <code>\r</code>). It returns <code>null</code> at end of stream. For the common case of reading a named file, <code>Files.newBufferedReader</code> does the same stacking in one call:</p>
<pre><code class="language-java">try (BufferedReader reader = Files.newBufferedReader(
        Path.of("message.txt"), StandardCharsets.UTF_8)) {
    String line;
    while ((line = reader.readLine()) != null) {
        process(line);
    }
}
</code></pre>
<p><code>Files.newBufferedReader</code> is available since Java 7 as part of NIO.2.</p>
<h2>For small files: Files.readString</h2>
<p>If the file fits in memory, <code>Files.readString</code> (Java 11+) is simpler:</p>
<pre><code class="language-java">String content = Files.readString(Path.of("message.txt"), StandardCharsets.UTF_8);
</code></pre>
<p>One call. The charset is explicit. Use this for config files, templates, test fixtures. For raw bytes, <code>Files.readAllBytes</code> does the same without decoding.</p>
<p>Large files shouldn't be loaded all at once. The right tool there is <code>Files.newBufferedReader</code> and line-by-line processing, or channels, which the next part covers.</p>
<h2>Exercise</h2>
<p>Write a method with this signature:</p>
<pre><code class="language-java">long countLines(Path path, Charset charset) throws IOException
</code></pre>
<p>It should count the number of newline-terminated lines in the file. What happens if you pass <code>StandardCharsets.ISO_8859_1</code> to a UTF-8 file that contains only ASCII characters? What about a file that contains 'á' (U+00E1)?</p>
<p>For the first case, every ASCII character has the same byte value in both UTF-8 and ISO-8859-1. The newline byte <code>0x0A</code> decodes identically in both charsets, so the line count is correct. For the second case, 'á' in UTF-8 is the two-byte sequence <code>0xC3 0xA1</code>. ISO-8859-1 decodes each byte separately, so <code>0xC3</code> becomes 'Ã' and <code>0xA1</code> becomes '¡'. The line count is still correct — neither byte is a newline — but every 'á' becomes two wrong characters.</p>
<p>The bytes didn't change. Only the interpretation did.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Java&apos;s Stream API: lazy pipelines and absent values</title>
      <link>https://unkletayo.dev/engineering/core-java/21-streams/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/21-streams/</guid>
      <description>Stream pipeline structure, source, intermediate, and terminal operations, lazy evaluation, map versus flatMap, common terminal operations and collectors, parallel streams, and Optional as a type-safe alternative to null returns.</description>
      <pubDate>Tue, 20 Oct 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>streams</category>
      <category>optional</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/21-streams.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/21-streams.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/21-streams.png" alt="Java&apos;s Stream API: lazy pipelines and absent values" /></p>
<pre><code class="language-java">List&lt;String&gt; names = List.of("alice", "bob", "charlie", "dave");
long count = 0;
for (String name : names) {
    if (name.length() &gt; 3) {
        count++;
    }
}
</code></pre>
<p>This is a loop over a known collection. Suppose the names came from a database query instead, returning ten million rows. The loop would hold ten million strings in memory before processing any. A stream processes elements one at a time, pulling from the source only as the terminal operation demands them.</p>
<h2>Pipeline structure</h2>
<p>A stream pipeline has three parts: a source, zero or more intermediate operations, and one terminal operation.</p>
<pre><code class="language-java">long count = names.stream()          // source
    .filter(n -&gt; n.length() &gt; 3)     // intermediate
    .count();                         // terminal
</code></pre>
<p>The source produces elements. Each intermediate operation transforms or filters the stream, returning a new stream. The terminal operation consumes the stream and produces a result (or a side effect). The source is not touched until the terminal operation runs.</p>
<h2>Laziness</h2>
<p>Intermediate operations are <strong>lazy</strong>: they describe transformations but do not execute them. Only the terminal operation triggers execution.</p>
<pre><code class="language-java">Stream&lt;String&gt; pipeline = names.stream()
    .filter(n -&gt; { System.out.println("filter: " + n); return n.length() &gt; 3; })
    .map(n -&gt; { System.out.println("map: " + n); return n.toUpperCase(); });

// Nothing has printed yet — the pipeline is defined but not running
long count = pipeline.count();  // execution starts here
</code></pre>
<p>When <code>count()</code> runs, elements flow through the pipeline one at a time. For each element: <code>filter</code> runs. If it passes, <code>map</code> runs on that element. Only then does the next element enter. The pipeline processes "alice", then "bob", then "charlie", and so on.</p>
<p>This matters for short-circuiting. <code>findFirst()</code> stops after finding the first matching element:</p>
<pre><code class="language-java">Optional&lt;String&gt; first = names.stream()
    .filter(n -&gt; n.length() &gt; 4)
    .findFirst();
// stops after finding "alice" (length 5); never touches "charlie" or "dave"
</code></pre>
<h2>Intermediate operations</h2>
<p><strong>filter:</strong> keeps elements matching a predicate.</p>
<pre><code class="language-java">.filter(n -&gt; n.startsWith("a"))
</code></pre>
<p><strong>map:</strong> transforms each element.</p>
<pre><code class="language-java">.map(String::toUpperCase)   // Stream&lt;String&gt; -&gt; Stream&lt;String&gt;
.map(String::length)        // Stream&lt;String&gt; -&gt; Stream&lt;Integer&gt;
</code></pre>
<p><strong>flatMap:</strong> transforms each element into a stream and flattens the results.</p>
<pre><code class="language-java">List&lt;List&lt;String&gt;&gt; groups = List.of(
    List.of("alice", "bob"),
    List.of("charlie", "dave")
);

groups.stream()
    .flatMap(Collection::stream)  // Stream&lt;List&lt;String&gt;&gt; -&gt; Stream&lt;String&gt;
    .forEach(System.out::println);
// alice, bob, charlie, dave
</code></pre>
<p>The difference between <code>map</code> and <code>flatMap</code>: <code>map</code> turns <code>Stream&lt;T&gt;</code> into <code>Stream&lt;R&gt;</code> by applying a function that returns <code>R</code>. <code>flatMap</code> turns <code>Stream&lt;T&gt;</code> into <code>Stream&lt;R&gt;</code> by applying a function that returns <code>Stream&lt;R&gt;</code> and merging the resulting streams. If you map to a <code>List</code>, you get <code>Stream&lt;List&lt;R&gt;&gt;</code>. If you flatMap to a stream, you get <code>Stream&lt;R&gt;</code>.</p>
<p><strong>sorted:</strong> sorts elements. Without an argument, requires the element type to be <code>Comparable</code>. Accepts a <code>Comparator</code>.</p>
<pre><code class="language-java">.sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))
</code></pre>
<p><strong>distinct:</strong> removes duplicates using <code>equals</code>.</p>
<p><strong>limit(n):</strong> keeps at most <code>n</code> elements.</p>
<p><strong>peek:</strong> applies a consumer for side effects, then passes the element through. Useful for debugging:</p>
<pre><code class="language-java">.peek(n -&gt; System.out.println("before filter: " + n))
.filter(n -&gt; n.length() &gt; 3)
.peek(n -&gt; System.out.println("after filter: " + n))
</code></pre>
<p>Do not use <code>peek</code> for anything beyond debugging. Its behavior depends on the terminal operation and is not guaranteed in all cases.</p>
<h2>Terminal operations</h2>
<p><strong>count:</strong> returns the number of elements as a <code>long</code>.</p>
<p><strong>forEach:</strong> applies a consumer to each element. No return value. Order is not guaranteed in parallel streams.</p>
<p><strong>collect:</strong> accumulates elements into a container. The most flexible terminal operation.</p>
<pre><code class="language-java">List&lt;String&gt; result = names.stream()
    .filter(n -&gt; n.length() &gt; 3)
    .collect(Collectors.toList());
</code></pre>
<p>Common collectors: <code>toList()</code>, <code>toSet()</code>, <code>toUnmodifiableList()</code>, <code>joining(delimiter)</code> for strings, <code>groupingBy(classifier)</code> for maps, <code>counting()</code>, <code>summingInt(mapper)</code>.</p>
<p><strong>findFirst / findAny:</strong> returns an <code>Optional&lt;T&gt;</code>. <code>findFirst</code> returns the first element in encounter order. <code>findAny</code> may return any element (useful in parallel streams where order doesn't matter).</p>
<p><strong>anyMatch / allMatch / noneMatch:</strong> short-circuiting predicates that return <code>boolean</code>.</p>
<p><strong>reduce:</strong> combines all elements into one.</p>
<pre><code class="language-java">int sum = IntStream.rangeClosed(1, 10).reduce(0, Integer::sum);  // 55
</code></pre>
<p><strong>toArray:</strong> materializes the stream into an array.</p>
<h2>Primitive streams</h2>
<p>Autoboxing <code>int</code> values into <code>Integer</code> for every element in a large stream is expensive. Java provides <code>IntStream</code>, <code>LongStream</code>, and <code>DoubleStream</code> for primitive elements.</p>
<pre><code class="language-java">int[] numbers = {1, 2, 3, 4, 5};
int sum = Arrays.stream(numbers).sum();  // IntStream, no boxing
</code></pre>
<p>You can convert between object streams and primitive streams: <code>stream.mapToInt(String::length)</code> returns an <code>IntStream</code>; <code>intStream.boxed()</code> returns a <code>Stream&lt;Integer&gt;</code>.</p>
<h2>Optional</h2>
<p><code>Optional&lt;T&gt;</code> is a container that holds either a value or nothing. It is designed for methods that may or may not return a result.</p>
<pre><code class="language-java">Optional&lt;String&gt; maybeFirst = names.stream()
    .filter(n -&gt; n.startsWith("z"))
    .findFirst();

// Check whether a value is present
if (maybeFirst.isPresent()) {
    System.out.println(maybeFirst.get());
}

// Or use orElse
String name = maybeFirst.orElse("not found");

// Or transform if present
int length = maybeFirst.map(String::length).orElse(0);

// Or throw if absent
String required = maybeFirst.orElseThrow(() -&gt; new IllegalStateException("expected a name"));
</code></pre>
<p><code>Optional</code> makes "this might be absent" visible in the type. A method that returns <code>String</code> could return <code>null</code>; a method that returns <code>Optional&lt;String&gt;</code> signals that absence is a possibility the caller should handle. The caller cannot accidentally dereference an <code>Optional</code> without first dealing with the absent case.</p>
<p>Do not use <code>Optional.get()</code> without first calling <code>isPresent()</code>. It throws <code>NoSuchElementException</code> when the value is absent, defeating the purpose. Prefer <code>orElse</code>, <code>orElseGet</code>, <code>map</code>, or <code>orElseThrow</code>.</p>
<p><code>Optional</code> is intended for return types, not for fields or parameters. A field of type <code>Optional&lt;T&gt;</code> can be null itself (an <code>Optional</code> that is null, rather than empty), which is confusing. A parameter of type <code>Optional&lt;T&gt;</code> forces the caller to wrap values in an <code>Optional</code> before calling, which is inconvenient. For optional fields, use a nullable field or a default value. For optional parameters, use overloading.</p>
<h2>Parallel streams</h2>
<p><code>.parallel()</code> or <code>Collection.parallelStream()</code> changes the stream to run on the common fork-join pool. The pool size defaults to one less than the number of available processors.</p>
<pre><code class="language-java">long count = names.parallelStream()
    .filter(n -&gt; expensiveCheck(n))
    .count();
</code></pre>
<p>Parallel streams are worth considering when the work per element is expensive and the collection is large. For small collections or cheap operations, the overhead of splitting and merging work is greater than the savings.</p>
<p>Parallel streams do not help when: the operations have side effects on shared state; the operations are inherently ordered and cannot be split; <code>forEach</code> is used in an order-dependent way. Stateful lambdas (capturing and modifying shared variables) in parallel streams produce data races.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">List&lt;Integer&gt; numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
int result = numbers.stream()
    .filter(n -&gt; n % 2 == 0)
    .mapToInt(n -&gt; n * n)
    .sum();
System.out.println(result);
</code></pre>
<p>Trace through the pipeline: which elements pass the filter, what does <code>mapToInt</code> produce for each, and what does <code>sum</code> return? Then: could you replace <code>mapToInt(n -&gt; n * n).sum()</code> with <code>map(n -&gt; n * n).reduce(0, Integer::sum)</code> and get the same result? The next article covers I/O: how Java reads and writes bytes and characters, what streams and buffers do, and how to process a file without loading it all into memory at once. <a href="https://unkletayo.dev/engineering/core-java/22-bytes-characters-and-encoding/">I/O: bytes, characters, and files</a> continues from here.</p>
]]></content:encoded>
    </item>
    <item>
      <title>How Java treats functions as values</title>
      <link>https://unkletayo.dev/engineering/core-java/20-lambdas/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/20-lambdas/</guid>
      <description>What functional interfaces are, how lambda expressions create instances of them, method references as a shorthand, variable capture and effectively-final variables, common functional interfaces from java.util.function, and how lambdas relate to anonymous classes.</description>
      <pubDate>Tue, 13 Oct 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>lambdas</category>
      <category>functionalinterfaces</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/20-lambdas.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/20-lambdas.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/20-lambdas.png" alt="How Java treats functions as values" /></p>
<p>A sorting method needs to know how to compare two elements. One way to pass that knowledge: a class that implements a comparison.</p>
<pre><code class="language-java">Comparator&lt;String&gt; byLength = new Comparator&lt;String&gt;() {
    @Override
    public int compare(String a, String b) {
        return Integer.compare(a.length(), b.length());
    }
};

List&lt;String&gt; words = new ArrayList&lt;&gt;(List.of("banana", "fig", "apple"));
words.sort(byLength);
System.out.println(words);  // [fig, apple, banana]
</code></pre>
<p>This works, but it is six lines for a single comparison. The object itself carries no state; it only carries behavior. Java 8 introduced a shorter way to express the same thing:</p>
<pre><code class="language-java">Comparator&lt;String&gt; byLength = (a, b) -&gt; Integer.compare(a.length(), b.length());
words.sort(byLength);
</code></pre>
<p>One line. Same result. This is a <strong>lambda expression</strong>: a compact syntax for creating an instance of an interface that has exactly one abstract method.</p>
<h2>Functional interfaces</h2>
<p>A <strong>functional interface</strong> is an interface with exactly one abstract method. <code>Comparator&lt;T&gt;</code> qualifies. <code>Runnable</code> qualifies (its one abstract method is <code>run()</code>). <code>Comparable&lt;T&gt;</code> qualifies.</p>
<p>An interface with two abstract methods is not functional, because a lambda has only one body to fill. The compiler rejects a lambda where a non-functional interface is expected.</p>
<p>The <code>@FunctionalInterface</code> annotation marks an interface as intentionally functional:</p>
<pre><code class="language-java">@FunctionalInterface
public interface Validator&lt;T&gt; {
    boolean isValid(T value);
}
</code></pre>
<p>The annotation is optional but useful. If someone accidentally adds a second abstract method to <code>Validator</code>, the compiler reports an error at the annotation rather than at every lambda that uses it.</p>
<h2>Lambda syntax</h2>
<p>The basic form is <code>(parameters) -&gt; body</code>:</p>
<pre><code class="language-java">// No parameters
Runnable r = () -&gt; System.out.println("running");

// One parameter (parentheses optional)
Validator&lt;String&gt; notEmpty = s -&gt; !s.isBlank();

// Two parameters
Comparator&lt;Integer&gt; descending = (a, b) -&gt; b - a;

// Block body for multiple statements
Comparator&lt;String&gt; complex = (a, b) -&gt; {
    int byLength = Integer.compare(a.length(), b.length());
    if (byLength != 0) return byLength;
    return a.compareTo(b);
};
</code></pre>
<p>The parameter types are inferred from the functional interface. When the body is a single expression, its value is returned implicitly. A block body needs an explicit <code>return</code> statement.</p>
<h2>Method references</h2>
<p>A method reference is a shorthand for a lambda that only calls a single existing method:</p>
<pre><code class="language-java">// Equivalent forms
words.forEach(word -&gt; System.out.println(word));
words.forEach(System.out::println);
</code></pre>
<p>There are four kinds:</p>
<p><strong>Static method:</strong> <code>ClassName::methodName</code></p>
<pre><code class="language-java">// (s) -&gt; Integer.parseInt(s)
Function&lt;String, Integer&gt; parse = Integer::parseInt;
</code></pre>
<p><strong>Instance method on a specific object:</strong> <code>instance::methodName</code></p>
<pre><code class="language-java">String prefix = "log: ";
// (s) -&gt; prefix.concat(s)
Function&lt;String, String&gt; addPrefix = prefix::concat;
</code></pre>
<p><strong>Instance method on the lambda's first parameter:</strong> <code>ClassName::methodName</code></p>
<pre><code class="language-java">// (s) -&gt; s.toUpperCase()
Function&lt;String, String&gt; upper = String::toUpperCase;
</code></pre>
<p><strong>Constructor:</strong> <code>ClassName::new</code></p>
<pre><code class="language-java">// (s) -&gt; new StringBuilder(s)
Function&lt;String, StringBuilder&gt; build = StringBuilder::new;
</code></pre>
<p>Method references are a readability choice. Use them when the method name communicates intent clearly. If the lambda does anything beyond a single method call, write it out.</p>
<h2>Variable capture</h2>
<p>A lambda can read variables from the surrounding scope. The variable must be <strong>effectively final</strong>: assigned exactly once and never reassigned after that.</p>
<pre><code class="language-java">int minLength = 4;
Validator&lt;String&gt; longEnough = s -&gt; s.length() &gt;= minLength;  // captures minLength
</code></pre>
<p><code>minLength</code> is captured by value, not by reference. The lambda holds a copy of the value at the moment of capture. Modifying <code>minLength</code> after the lambda is created would be a compile error (effectively final rule), so the copy is always correct.</p>
<pre><code class="language-java">int count = 0;
Runnable r = () -&gt; count++;  // compile error: count is not effectively final
</code></pre>
<p>This restriction comes from the way lambdas are implemented. A lambda does not hold a reference to the enclosing stack frame; it captures copies of the values it needs. Allowing mutation of a local variable would require storing the variable on the heap, which is what anonymous classes do with field capture. Java chose the simpler rule: if you need a mutable captured value, use an array or a wrapper class as a one-element mutable container:</p>
<pre><code class="language-java">int[] count = {0};
Runnable r = () -&gt; count[0]++;  // captures the array reference (effectively final)
r.run();
System.out.println(count[0]);  // 1
</code></pre>
<p>Instance fields (<code>this.count</code>) and static fields can be read and modified from within a lambda freely. Only local variables are constrained by the effectively-final rule.</p>
<h2>Common functional interfaces in java.util.function</h2>
<p>Java provides a set of generic functional interfaces for the most common shapes:</p>
<p><code>Supplier&lt;T&gt;</code>: no argument, returns <code>T</code>. <code>() -&gt; new ArrayList&lt;&gt;()</code>.</p>
<p><code>Consumer&lt;T&gt;</code>: takes <code>T</code>, returns nothing. <code>item -&gt; log(item)</code>.</p>
<p><code>Function&lt;T, R&gt;</code>: takes <code>T</code>, returns <code>R</code>. <code>s -&gt; s.length()</code>.</p>
<p><code>Predicate&lt;T&gt;</code>: takes <code>T</code>, returns <code>boolean</code>. <code>s -&gt; s.isEmpty()</code>.</p>
<p><code>BiFunction&lt;T, U, R&gt;</code>: takes <code>T</code> and <code>U</code>, returns <code>R</code>. <code>(a, b) -&gt; a + b</code>.</p>
<p><code>UnaryOperator&lt;T&gt;</code>: takes <code>T</code>, returns <code>T</code>. A <code>Function&lt;T, T&gt;</code> with a clearer name. <code>s -&gt; s.trim()</code>.</p>
<p><code>BinaryOperator&lt;T&gt;</code>: takes two <code>T</code>, returns <code>T</code>. A <code>BiFunction&lt;T, T, T&gt;</code> with a clearer name. <code>(a, b) -&gt; a + b</code>.</p>
<p>The package also has primitive specializations: <code>IntSupplier</code>, <code>LongFunction&lt;R&gt;</code>, <code>IntUnaryOperator</code>, and so on. Use them when the type involved is a primitive; they avoid the autoboxing that the generic versions require.</p>
<h2>Lambdas versus anonymous classes</h2>
<p>A lambda creates an instance of a functional interface. An anonymous class also creates an instance of an interface (or abstract class). They overlap, but they are not identical.</p>
<p>The key difference is <code>this</code>. Inside an anonymous class, <code>this</code> refers to the anonymous class instance. Inside a lambda, <code>this</code> refers to the enclosing instance. If you need <code>this</code> inside the behavior, you need an anonymous class.</p>
<pre><code class="language-java">// 'this' inside lambda refers to the enclosing class instance
Runnable r = () -&gt; System.out.println(this.getClass().getName());

// 'this' inside anonymous class refers to the anonymous class
Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println(this.getClass().getName());  // anonymous class
    }
};
</code></pre>
<p>Lambdas also cannot extend a class; they can only implement a functional interface. Anonymous classes can extend a class or implement any interface.</p>
<p>Another difference: each anonymous class <code>new Foo() { ... }</code> always creates a new class. Lambdas are compiled differently; the JVM may share class definitions across lambda instances and may elide allocations when the lambda captures nothing. In practice, prefer lambdas for their brevity and clarity; use anonymous classes only when you need <code>this</code> to refer to the anonymous instance or when implementing a non-functional interface.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">List&lt;String&gt; words = List.of("apple", "fig", "banana", "date");
String result = words.stream()
    .filter(w -&gt; w.length() &gt; 3)
    .sorted(Comparator.comparingInt(String::length).reversed())
    .findFirst()
    .orElse("none");
System.out.println(result);
</code></pre>
<p>Work through the steps: which words pass the filter, what order does <code>sorted</code> produce, and what does <code>findFirst</code> return? The next article covers streams in full: how the pipeline processes elements lazily, what <code>map</code> and <code>flatMap</code> do, and how collectors aggregate results. <a href="https://unkletayo.dev/engineering/core-java/21-streams/">Streams and Optional</a> continues from here.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Generics: erasure, raw types, and what the compiler actually does</title>
      <link>https://unkletayo.dev/engineering/core-java/19-generics-erasure/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/19-generics-erasure/</guid>
      <description>How Java implements generics through type erasure, what the compiler substitutes for type parameters in bytecode, bridge methods, raw types and their relationship to unchecked warnings, and the practical restrictions that follow from erasure.</description>
      <pubDate>Tue, 06 Oct 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>generics</category>
      <category>typeerasure</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/19-generics-erasure.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/19-generics-erasure.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/19-generics-erasure.png" alt="Generics: erasure, raw types, and what the compiler actually does" /></p>
<p>A <code>Box&lt;String&gt;</code> and a <code>Box&lt;Integer&gt;</code> are the same class at runtime.</p>
<pre><code class="language-java">Box&lt;String&gt; stringBox = new Box&lt;&gt;("hello");
Box&lt;Integer&gt; intBox = new Box&lt;&gt;(42);

System.out.println(stringBox.getClass() == intBox.getClass());  // true
System.out.println(stringBox.getClass().getName());             // Box
</code></pre>
<p>Both print as <code>Box</code>. Not <code>Box&lt;String&gt;</code> and <code>Box&lt;Integer&gt;</code>. Type parameters do not exist in bytecode. The compiler uses them to check types during compilation, then removes them. This is <strong>type erasure</strong>.</p>
<h2>What erasure means</h2>
<p>When the compiler compiles a generic class, it replaces each type parameter with its bound, or with <code>Object</code> if there is no bound.</p>
<p>For <code>Box&lt;T&gt;</code>:</p>
<pre><code class="language-java">// Source
public class Box&lt;T&gt; {
    private T value;
    public T get() { return value; }
}

// After erasure (what the compiler produces)
public class Box {
    private Object value;
    public Object get() { return value; }
}
</code></pre>
<p>For <code>Box&lt;T extends Comparable&lt;T&gt;&gt;</code>:</p>
<pre><code class="language-java">// Source
public class BoundedBox&lt;T extends Comparable&lt;T&gt;&gt; {
    private T value;
    public T get() { return value; }
    public boolean isGreaterThan(T other) { return value.compareTo(other) &gt; 0; }
}

// After erasure
public class BoundedBox {
    private Comparable value;
    public Comparable get() { return value; }
    public boolean isGreaterThan(Comparable other) { return value.compareTo(other) &gt; 0; }
}
</code></pre>
<p>The upper bound becomes the erased type. <code>Comparable</code>, not <code>Object</code>.</p>
<p>At the <strong>call site</strong>, the compiler inserts casts where needed:</p>
<pre><code class="language-java">// Source
Box&lt;String&gt; box = new Box&lt;&gt;("hello");
String s = box.get();

// After erasure
Box box = new Box("hello");
String s = (String) box.get();  // compiler inserts cast
</code></pre>
<p>The cast is generated for you. As long as you used the generic type correctly, it never fails. If you use a raw type (see below) and put the wrong type in, the cast you never saw fails at runtime.</p>
<h2>Bridge methods</h2>
<p>Erasure creates a subtlety with inheritance. Suppose you have:</p>
<pre><code class="language-java">public class StringBox extends Box&lt;String&gt; {
    @Override
    public String get() { return ...; }
}
</code></pre>
<p>After erasure, <code>Box.get()</code> returns <code>Object</code>. <code>StringBox.get()</code> returns <code>String</code>. These are different method signatures, so <code>StringBox.get()</code> is not technically overriding <code>Box.get()</code> in bytecode.</p>
<p>The compiler generates a <strong>bridge method</strong> to fix this:</p>
<pre><code class="language-java">// Generated by compiler, not in source
public Object get() {
    return (Object) this.get();  // calls the String version
}
</code></pre>
<p>The bridge method has the erased signature from the parent class and delegates to the covariant override. This keeps polymorphism working correctly through erased types. You will occasionally see bridge methods in stack traces or when inspecting a class with reflection; they are always labeled synthetic.</p>
<h2>Restrictions that follow from erasure</h2>
<p><strong>You cannot use <code>instanceof</code> with a type parameter.</strong> At runtime, <code>T</code> is gone. <code>x instanceof T</code> has nothing to check against.</p>
<pre><code class="language-java">public &lt;T&gt; boolean isInstance(Object x) {
    return x instanceof T;  // compile error
}
</code></pre>
<p>The workaround is to pass a <code>Class&lt;T&gt;</code> parameter:</p>
<pre><code class="language-java">public &lt;T&gt; boolean isInstance(Object x, Class&lt;T&gt; type) {
    return type.isInstance(x);
}
</code></pre>
<p><strong>You cannot create instances or arrays of a type parameter.</strong></p>
<pre><code class="language-java">T value = new T();       // compile error
T[] array = new T[10];   // compile error
</code></pre>
<p>For instance creation, the workaround is to pass a <code>Supplier&lt;T&gt;</code> or <code>Class&lt;T&gt;</code>. For arrays, use <code>Object[]</code> and cast, or use a <code>List&lt;T&gt;</code> instead.</p>
<p><strong>You cannot catch a generic exception type.</strong> <code>catch (T e)</code> is a compile error because exception handling uses runtime types.</p>
<p><strong>Static fields cannot have a generic type.</strong> <code>static T value</code> is a compile error. Static members belong to the class itself, not to any parameterization of it, and there is only one class at runtime.</p>
<h2>Raw types</h2>
<p>A <strong>raw type</strong> is a generic class used without its type argument:</p>
<pre><code class="language-java">Box rawBox = new Box("hello");  // raw type
Object value = rawBox.get();    // returns Object, no type info
</code></pre>
<p>Raw types exist for backward compatibility with pre-generics Java (before Java 5). The compiler treats a raw type as if its type parameters were all <code>Object</code>. It allows the use but emits an <strong>unchecked warning</strong> to signal that type safety is no longer guaranteed.</p>
<pre><code class="language-java">Box rawBox = new Box(42);
String s = (String) rawBox.get();  // compiles with warning, ClassCastException at runtime
</code></pre>
<p>The warning is "Unchecked or unsafe operation". It means you have stepped outside the generic type system and the compiler can no longer protect you.</p>
<p>Do not use raw types in new code. They were acceptable in Java 1.4 code that predates generics; in modern Java, every use of a generic type should provide its type argument. When working with legacy APIs that return raw types, cast to the parameterized type and understand that you are assuming the correctness the compiler cannot verify.</p>
<p>Unchecked warnings can be suppressed with <code>@SuppressWarnings("unchecked")</code>, but do so only when you have verified the assumption by other means and can explain why it holds.</p>
<h2>Reifiable types</h2>
<p>A type is <strong>reifiable</strong> if its full type information is available at runtime: <code>String</code>, <code>int[]</code>, <code>List</code> (raw), <code>List&lt;?&gt;</code>. A <code>List&lt;String&gt;</code> is not reifiable because the <code>String</code> part is erased.</p>
<p>This matters for arrays. Java allows arrays of reifiable types (<code>String[]</code>, <code>Object[]</code>, <code>List&lt;?&gt;[]</code>) but not arrays of non-reifiable parameterized types (<code>List&lt;String&gt;[]</code>). The compiler rejects the latter because it cannot enforce type safety through the combination of array covariance and generic erasure.</p>
<p>If you need a collection of a parameterized type, use <code>List&lt;List&lt;String&gt;&gt;</code> instead of <code>List&lt;String&gt;[]</code>.</p>
<h2>Heap pollution</h2>
<p><strong>Heap pollution</strong> occurs when a variable of a parameterized type refers to an object that is not of that parameterized type. This is the runtime consequence of using raw types or unchecked casts incorrectly:</p>
<pre><code class="language-java">List rawList = new ArrayList&lt;Integer&gt;();
rawList.add("not an integer");        // no compile error on raw list

List&lt;Integer&gt; typedList = rawList;    // unchecked warning
Integer value = typedList.get(0);     // ClassCastException here
</code></pre>
<p>The <code>ClassCastException</code> appears at <code>typedList.get(0)</code>, not at the line where the string was added. The mismatch happened earlier, but erasure hid it until a cast was needed. Heap pollution makes bugs hard to trace because the exception occurs far from the cause.</p>
<p>The <code>@SafeVarargs</code> annotation (Java 7+) suppresses unchecked warnings on varargs methods that use a generic type, when the author has verified that the method does not cause heap pollution. It is a promise to the compiler, not a guarantee.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public static &lt;T&gt; T[] toArray(List&lt;T&gt; list) {
    T[] array = (T[]) new Object[list.size()];
    for (int i = 0; i &lt; list.size(); i++) {
        array[i] = list.get(i);
    }
    return array;
}

String[] result = toArray(List.of("a", "b", "c"));
</code></pre>
<p>Does this compile? Does it run without error? What exception, if any, is thrown and on which line? Then: why does this fail when the equivalent with <code>Object[]</code> would not? The next article moves to functional interfaces and lambdas: how Java represents a behavior as a value. <a href="https://unkletayo.dev/engineering/core-java/20-lambdas/">Functional interfaces and lambdas</a> continues from here.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Generics: wildcards and when to use them</title>
      <link>https://unkletayo.dev/engineering/core-java/18-generics-wildcards/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/18-generics-wildcards/</guid>
      <description>What wildcards are in Java generics, the difference between unbounded, upper bounded (? extends T), and lower bounded (? super T) wildcards, the producer-extends-consumer-super rule, and when to use a wildcard versus a type parameter.</description>
      <pubDate>Tue, 29 Sep 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>generics</category>
      <category>wildcards</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/18-generics-wildcards.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/18-generics-wildcards.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/18-generics-wildcards.png" alt="Generics: wildcards and when to use them" /></p>
<pre><code class="language-java">public static double sumList(List&lt;Number&gt; numbers) {
    double total = 0;
    for (Number n : numbers) {
        total += n.doubleValue();
    }
    return total;
}
</code></pre>
<p>This compiles. But when you try to pass a <code>List&lt;Integer&gt;</code>:</p>
<pre><code class="language-java">List&lt;Integer&gt; ints = List.of(1, 2, 3);
System.out.println(sumList(ints));  // compile error
</code></pre>
<p>The error: "incompatible types: <code>List&lt;Integer&gt;</code> cannot be converted to <code>List&lt;Number&gt;</code>".</p>
<p><code>Integer</code> is a subtype of <code>Number</code>. So why does <code>List&lt;Integer&gt;</code> not count as a <code>List&lt;Number&gt;</code>?</p>
<h2>Why generic types are not covariant</h2>
<p>Consider what would happen if <code>List&lt;Integer&gt;</code> were assignable to <code>List&lt;Number&gt;</code>:</p>
<pre><code class="language-java">List&lt;Integer&gt; ints = new ArrayList&lt;&gt;();
List&lt;Number&gt; numbers = ints;      // suppose this compiled
numbers.add(3.14);                // adds a Double into the Integer list
Integer n = ints.get(0);         // ClassCastException
</code></pre>
<p>Adding a <code>Double</code> to a <code>List&lt;Number&gt;</code> would put a non-<code>Integer</code> into what <code>ints</code> sees as a <code>List&lt;Integer&gt;</code>. The type system would be unsound. Java prevents this by making generic types <strong>invariant</strong>: <code>List&lt;Integer&gt;</code> is not a subtype of <code>List&lt;Number&gt;</code>, even though <code>Integer</code> is a subtype of <code>Number</code>.</p>
<p>Arrays are covariant in Java, which is why this compiles and throws at runtime:</p>
<pre><code class="language-java">Integer[] ints = {1, 2};
Number[] numbers = ints;         // allowed (arrays are covariant)
numbers[0] = 3.14;               // ArrayStoreException at runtime
</code></pre>
<p>Generics fix this by moving the check to compile time.</p>
<h2>Upper bounded wildcards: <code>? extends T</code></h2>
<p>To accept a list of <code>Number</code> or any subtype of <code>Number</code>, use an upper bounded wildcard:</p>
<pre><code class="language-java">public static double sumList(List&lt;? extends Number&gt; numbers) {
    double total = 0;
    for (Number n : numbers) {
        total += n.doubleValue();
    }
    return total;
}
</code></pre>
<p>Now <code>sumList(ints)</code> compiles. <code>List&lt;? extends Number&gt;</code> matches <code>List&lt;Integer&gt;</code>, <code>List&lt;Double&gt;</code>, <code>List&lt;Float&gt;</code>, and <code>List&lt;Number&gt;</code> itself.</p>
<p>The tradeoff: you can read from a <code>List&lt;? extends Number&gt;</code> safely (each element is at least a <code>Number</code>), but you cannot write to it. The compiler rejects <code>numbers.add(42)</code> because it cannot guarantee the actual list type. If <code>numbers</code> is a <code>List&lt;Integer&gt;</code>, adding a <code>Double</code> would corrupt it. The wildcard makes the list read-only from the compiler's perspective.</p>
<h2>Lower bounded wildcards: <code>? super T</code></h2>
<p>The opposite situation: a list you want to write <code>Integer</code> values into, without caring whether it was declared as <code>List&lt;Integer&gt;</code>, <code>List&lt;Number&gt;</code>, or <code>List&lt;Object&gt;</code>:</p>
<pre><code class="language-java">public static void fillWithZero(List&lt;? super Integer&gt; list, int count) {
    for (int i = 0; i &lt; count; i++) {
        list.add(0);
    }
}
</code></pre>
<p><code>List&lt;? super Integer&gt;</code> matches any list whose element type is <code>Integer</code> or a supertype of <code>Integer</code>. Adding <code>0</code> (an <code>Integer</code>) to any such list is safe: a <code>List&lt;Number&gt;</code> accepts <code>Integer</code>, a <code>List&lt;Object&gt;</code> accepts <code>Integer</code>.</p>
<p>The tradeoff: you can write <code>Integer</code> values into a <code>List&lt;? super Integer&gt;</code>, but reading out a specific type is not safe. <code>list.get(0)</code> returns <code>Object</code>, not <code>Integer</code>, because the list might contain elements added elsewhere of a type other than <code>Integer</code>.</p>
<h2>PECS: producer extends, consumer super</h2>
<p>The rule that follows from the two wildcards:</p>
<p>If a parameter only <strong>produces</strong> values you read from it, use <code>? extends T</code>. The list gives you values; it is the producer.</p>
<p>If a parameter only <strong>consumes</strong> values you write into it, use <code>? super T</code>. The list accepts values; it is the consumer.</p>
<p>If a parameter does both, use a plain type parameter.</p>
<pre><code class="language-java">// source produces; dest consumes
public static &lt;T&gt; void copy(List&lt;? extends T&gt; source, List&lt;? super T&gt; dest) {
    for (T item : source) {
        dest.add(item);
    }
}
</code></pre>
<p>This signature accepts <code>copy(List&lt;Integer&gt; source, List&lt;Number&gt; dest)</code> even though <code>Integer</code> and <code>Number</code> are different types, because the bounds make the variance explicit.</p>
<p>The name "PECS" comes from Joshua Bloch's <em>Effective Java</em>. It is a mnemonic for the direction of data flow, not a law separate from the type rules above.</p>
<h2>Unbounded wildcards: <code>?</code></h2>
<p><code>List&lt;?&gt;</code> matches any parameterized list regardless of element type. It is the most permissive wildcard.</p>
<pre><code class="language-java">public static void printSize(List&lt;?&gt; list) {
    System.out.println(list.size());
}
</code></pre>
<p>You can call methods that do not depend on the element type (like <code>size()</code>, <code>isEmpty()</code>, <code>clear()</code>). You cannot add elements (except <code>null</code>, which the compiler allows but that is usually wrong). Reading returns <code>Object</code>.</p>
<p>Use <code>List&lt;?&gt;</code> when your code genuinely does not care about the element type. If your code uses the elements as a specific type, use a bounded wildcard or a type parameter.</p>
<h2>Wildcard versus type parameter</h2>
<p>Both <code>&lt;T&gt; void process(List&lt;T&gt; list)</code> and <code>void process(List&lt;?&gt; list)</code> express "a list of some element type." The difference is whether the element type needs a name.</p>
<p>If you use the type in more than one place in the signature, or in the return type, use a type parameter:</p>
<pre><code class="language-java">// T appears twice: input list and return type
public static &lt;T&gt; T first(List&lt;T&gt; list) {
    return list.get(0);
}
</code></pre>
<p>If the element type appears only once and you never need to refer to it, a wildcard is simpler:</p>
<pre><code class="language-java">public static void printAll(List&lt;?&gt; list) {
    for (Object o : list) {
        System.out.println(o);
    }
}
</code></pre>
<p>Using a type parameter <code>&lt;T&gt;</code> where you never use <code>T</code> by name adds a meaningless constraint. Wildcards are more precise in that case.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public static &lt;T extends Comparable&lt;T&gt;&gt; void sort(List&lt;T&gt; list) {
    // bubble sort for illustration
    for (int i = 0; i &lt; list.size() - 1; i++) {
        for (int j = 0; j &lt; list.size() - 1 - i; j++) {
            if (list.get(j).compareTo(list.get(j + 1)) &gt; 0) {
                T temp = list.get(j);
                list.set(j, list.get(j + 1));
                list.set(j + 1, temp);
            }
        }
    }
}
</code></pre>
<p>Can you call <code>sort</code> with a <code>List&lt;Integer&gt;</code>? With a <code>List&lt;Object&gt;</code>? With a <code>List&lt;String&gt;</code>? For the case that fails, explain which bound is violated and what signature would fix it. The next article covers what happens to type parameters after compilation: erasure, the bridge methods the compiler generates, and what raw types are. <a href="https://unkletayo.dev/engineering/core-java/19-generics-erasure/">Generics: erasure and raw types</a> continues from here.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Generics: writing code that works for more than one type</title>
      <link>https://unkletayo.dev/engineering/core-java/17-generics-type-parameters/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/17-generics-type-parameters/</guid>
      <description>What problem generics solve, how to declare and use type parameters on classes and methods, upper bounded type parameters with extends, the type safety the compiler enforces, and the difference between generic classes and generic methods.</description>
      <pubDate>Tue, 22 Sep 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>generics</category>
      <category>typesafety</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/17-generics-type-parameters.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/17-generics-type-parameters.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/17-generics-type-parameters.png" alt="Generics: writing code that works for more than one type" /></p>
<p>Suppose you need a simple container that holds a single value and lets you read it back. For integers:</p>
<pre><code class="language-java">public class IntBox {
    private int value;
    public IntBox(int value) { this.value = value; }
    public int get() { return this.value; }
}
</code></pre>
<p>Then you need the same thing for strings. And doubles. And accounts. You write <code>StringBox</code>, <code>DoubleBox</code>, <code>AccountBox</code>. Each class is identical except for the type name.</p>
<p>There is a better way. Generics let you write the container once and use it with any type:</p>
<pre><code class="language-java">public class Box&lt;T&gt; {
    private T value;
    public Box(T value) { this.value = value; }
    public T get() { return this.value; }
}
</code></pre>
<p><code>T</code> is a <strong>type parameter</strong>: a placeholder that the caller fills in when they use the class. <code>Box&lt;String&gt;</code> is <code>Box</code> where <code>T</code> is <code>String</code>. <code>Box&lt;Integer&gt;</code> is <code>Box</code> where <code>T</code> is <code>Integer</code>. The same class, the same logic, two distinct types at the call site.</p>
<h2>How type parameters work</h2>
<p>A type parameter is declared in angle brackets after the class name: <code>class Box&lt;T&gt;</code>. Inside the class, <code>T</code> is usable as if it were a real type. Fields can be of type <code>T</code>. Methods can return <code>T</code>. Constructors can take <code>T</code> as a parameter.</p>
<p>The caller provides the actual type when constructing an instance:</p>
<pre><code class="language-java">Box&lt;String&gt; nameBox = new Box&lt;&gt;("Adetayo");
Box&lt;Integer&gt; countBox = new Box&lt;&gt;(42);
</code></pre>
<p>The compiler now knows that <code>nameBox.get()</code> returns a <code>String</code> and <code>countBox.get()</code> returns an <code>Integer</code>. You do not need a cast:</p>
<pre><code class="language-java">String name = nameBox.get();     // no cast needed
Integer count = countBox.get();  // no cast needed
</code></pre>
<p>Before generics (Java 1.4 and earlier), collections held <code>Object</code>. Every retrieval required a cast, and a wrong cast caused <code>ClassCastException</code> at runtime. With generics, the wrong type is a compiler error:</p>
<pre><code class="language-java">Box&lt;Integer&gt; box = new Box&lt;&gt;(42);
String s = box.get();  // compile error: incompatible types
</code></pre>
<p>The error appears at compile time, not at runtime. That is the core value of generics: type mistakes that would previously crash your program at runtime become errors the compiler catches during the build.</p>
<h2>Type inference</h2>
<p>You can often omit the type argument on the right side of a declaration, and the compiler infers it from the left side. This is called the <strong>diamond operator</strong>:</p>
<pre><code class="language-java">Box&lt;String&gt; nameBox = new Box&lt;&gt;("Adetayo");  // compiler infers Box&lt;String&gt;
</code></pre>
<p>The diamond <code>&lt;&gt;</code> tells the compiler to infer the type parameter from context. When inference is unambiguous, using the diamond makes the code less repetitive. When the type is not obvious from context, writing it out is clearer.</p>
<h2>Multiple type parameters</h2>
<p>A class can have more than one type parameter:</p>
<pre><code class="language-java">public class Pair&lt;A, B&gt; {
    private final A first;
    private final B second;

    public Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public A getFirst() { return first; }
    public B getSecond() { return second; }
}
</code></pre>
<pre><code class="language-java">Pair&lt;String, Integer&gt; entry = new Pair&lt;&gt;("totalItems", 42);
System.out.println(entry.getFirst());   // "totalItems"
System.out.println(entry.getSecond());  // 42
</code></pre>
<p>By convention, single-letter uppercase names are used for type parameters: <code>T</code> for a general type, <code>K</code> and <code>V</code> for key and value in maps, <code>E</code> for element in collections, <code>R</code> for a return type in functions. These conventions are not enforced; they communicate intent.</p>
<h2>Bounded type parameters</h2>
<p>A type parameter can require that the actual type satisfy a constraint. <code>&lt;T extends Comparable&lt;T&gt;&gt;</code> means "T must implement <code>Comparable&lt;T&gt;</code>":</p>
<pre><code class="language-java">public static &lt;T extends Comparable&lt;T&gt;&gt; T max(T a, T b) {
    return a.compareTo(b) &gt;= 0 ? a : b;
}
</code></pre>
<p>Without the bound, the compiler rejects <code>a.compareTo(b)</code> because it has no guarantee that <code>T</code> has that method. With the bound, <code>compareTo</code> is available because any type that satisfies <code>extends Comparable&lt;T&gt;</code> is guaranteed to implement it.</p>
<pre><code class="language-java">System.out.println(max("apple", "banana"));  // banana
System.out.println(max(10, 7));              // 10
</code></pre>
<p>The constraint is checked at the call site. <code>max(new Object(), new Object())</code> would fail to compile because <code>Object</code> does not implement <code>Comparable</code>.</p>
<p>Bounds can combine multiple interfaces with <code>&amp;</code>:</p>
<pre><code class="language-java">public &lt;T extends Serializable &amp; Comparable&lt;T&gt;&gt; void process(T item) { ... }
</code></pre>
<p><code>T</code> must implement both <code>Serializable</code> and <code>Comparable&lt;T&gt;</code>. Classes come before interfaces in the bound list; a class bound, if present, must be first.</p>
<h2>Generic methods</h2>
<p>A generic method declares its own type parameter, independent of the class. You saw this with <code>max</code> above. The type parameter is declared before the return type:</p>
<pre><code class="language-java">public static &lt;T&gt; void swap(T[] array, int i, int j) {
    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
</code></pre>
<p>The caller does not need to provide the type argument explicitly; the compiler infers it from the array type:</p>
<pre><code class="language-java">String[] words = {"hello", "world"};
swap(words, 0, 1);
System.out.println(Arrays.toString(words));  // [world, hello]
</code></pre>
<p>A method can be generic even if its class is not. This is the right choice when the type parameter is local to that one operation and does not appear in any field.</p>
<h2>What you cannot do with a type parameter</h2>
<p>There are four restrictions that follow from how Java implements generics. All four are covered in depth in the next article on erasure, but it helps to see them now.</p>
<p>You cannot create an instance: <code>new T()</code> is a compile error. The compiler does not know what constructor <code>T</code> has, because <code>T</code> could be any type.</p>
<p>You cannot create an array of a generic type: <code>new T[10]</code> is a compile error. This is a consequence of how Java arrays track their component type at runtime; type parameters are not available at runtime.</p>
<p>You cannot use a type parameter in a <code>static</code> context. <code>static T defaultValue</code> is a compile error. Static members belong to the class, not to any particular parameterized use of the class.</p>
<p>You cannot test with <code>instanceof T</code>: <code>x instanceof T</code> is a compile error. The runtime does not have type information for <code>T</code> after compilation.</p>
<p>Each restriction has a workaround, and understanding erasure explains why they exist. That is the subject of a later article.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public static &lt;T&gt; List&lt;T&gt; repeat(T item, int times) {
    List&lt;T&gt; result = new ArrayList&lt;&gt;();
    for (int i = 0; i &lt; times; i++) {
        result.add(item);
    }
    return result;
}
</code></pre>
<p>What does <code>repeat("x", 3)</code> return? What does <code>repeat(null, 2)</code> return? Then: does <code>repeat(42, 3)</code> compile? If so, is the return type <code>List&lt;Integer&gt;</code> or <code>List&lt;int&gt;</code>? The next article covers wildcards, the <code>extends</code> and <code>super</code> bounds you use with them, and why you need a different kind of bound when you are reading from a collection versus writing to one. <a href="https://unkletayo.dev/engineering/core-java/18-generics-wildcards/">Generics: wildcards and variance</a> continues from here.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Exception design: try-with-resources, chaining, and custom types</title>
      <link>https://unkletayo.dev/engineering/core-java/16-exception-design/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/16-exception-design/</guid>
      <description>try-with-resources and AutoCloseable, exception chaining with getCause(), designing custom checked and unchecked exception types, the checked-versus-unchecked decision for your own API, and common exception-handling mistakes to avoid.</description>
      <pubDate>Tue, 15 Sep 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>exceptions</category>
      <category>apidesign</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/16-exception-design.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/16-exception-design.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/16-exception-design.png" alt="Exception design: try-with-resources, chaining, and custom types" /></p>
<pre><code class="language-java">public static String readFirstLine(Path path) throws IOException {
    FileInputStream fis = new FileInputStream(path.toFile());
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader reader = new BufferedReader(isr);
    String line = reader.readLine();
    reader.close();
    return line;
}
</code></pre>
<p>This compiles and runs. It also leaks resources when <code>readLine()</code> throws an exception, because <code>reader.close()</code> never executes. If <code>close()</code> itself throws, it replaces whatever exception <code>readLine()</code> raised, losing the original failure reason. And it closes only <code>reader</code>, leaving <code>isr</code> and <code>fis</code> open.</p>
<p>Three separate problems, one common pattern. Java solved them together.</p>
<h2>try-with-resources</h2>
<p>A <strong>resource</strong> in Java is any object whose class implements <code>AutoCloseable</code>. The <code>close()</code> method is called automatically when the block exits.</p>
<pre><code class="language-java">try (FileInputStream fis = new FileInputStream(path.toFile());
     InputStreamReader isr = new InputStreamReader(fis);
     BufferedReader reader = new BufferedReader(isr)) {
    return reader.readLine();
}
</code></pre>
<p>The compiler generates a <code>finally</code> block that calls <code>close()</code> on each resource, in reverse order of declaration. <code>reader</code> closes first, then <code>isr</code>, then <code>fis</code>. Reverse order matters: <code>reader</code> wraps <code>isr</code>, which wraps <code>fis</code>, so closing the outermost first flushes any internal buffers before the underlying streams close.</p>
<p>What happens when both the <code>try</code> block and <code>close()</code> throw? The <code>close()</code> exception is <strong>suppressed</strong>: it is attached to the original exception but does not replace it. You can inspect suppressed exceptions with <code>e.getSuppressed()</code>. Without try-with-resources, a <code>close()</code> exception silently discards the original failure. That makes diagnosis impossible: the stack trace points to <code>close()</code>, not to the actual problem.</p>
<p>Use try-with-resources for every <code>Closeable</code> or <code>AutoCloseable</code>: files, streams, database connections, <code>PreparedStatement</code>, JDBC result sets, HTTP clients with explicit close methods. If the type implements <code>AutoCloseable</code>, do not manage its lifetime in a <code>finally</code> block.</p>
<p>You can also implement <code>AutoCloseable</code> in your own classes:</p>
<pre><code class="language-java">public class MeasuredScope implements AutoCloseable {
    private final String name;
    private final long startNanos;

    public MeasuredScope(String name) {
        this.name = name;
        this.startNanos = System.nanoTime();
    }

    @Override
    public void close() {
        long elapsed = System.nanoTime() - startNanos;
        System.out.printf("%s: %d ms%n", name, elapsed / 1_000_000);
    }
}

try (MeasuredScope scope = new MeasuredScope("parse")) {
    parseDocument(input);
}
</code></pre>
<p><code>close()</code> does not need to release a system resource. It runs at the end of the block regardless, so it works for anything where "execute this cleanup code" is useful.</p>
<h2>Exception chaining</h2>
<p>When you catch an exception and throw a different one, preserve the original as the cause:</p>
<pre><code class="language-java">} catch (IOException e) {
    throw new DataAccessException("Failed to load configuration", e);
}
</code></pre>
<p>The <code>Throwable cause</code> argument is the second parameter in the standard exception constructors. The cause is accessible via <code>getCause()</code> and appears in the stack trace as "Caused by:":</p>
<pre><code>Exception in thread "main" com.example.DataAccessException: Failed to load configuration
	at com.example.ConfigLoader.load(ConfigLoader.java:31)
	at com.example.Main.main(Main.java:12)
Caused by: java.io.FileNotFoundException: /etc/app/config.json (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	...
</code></pre>
<p>Without the cause, your <code>DataAccessException</code> appears to have no origin. Someone diagnosing a production failure sees only "Failed to load configuration" and has to guess what actually went wrong. The "Caused by:" chain shows the full picture.</p>
<p>The cause is useful in both directions: catching a low-level checked exception and re-throwing as an unchecked exception (wrapping), and catching an unchecked exception to add domain context (enriching). In both cases, pass the original.</p>
<p>Do not catch an exception, log it, and then re-throw it. That produces a duplicate log entry for the same failure. Either log it and swallow it (acceptable when you have genuinely handled it), or re-throw it and let the caller log it. Doing both means every handler in the call stack logs the same event.</p>
<h2>Custom exception types</h2>
<p>When you need a checked exception for a recoverable condition in your domain, create a subclass of <code>Exception</code>:</p>
<pre><code class="language-java">public class InsufficientFundsException extends Exception {
    private final int requested;
    private final int available;

    public InsufficientFundsException(int requested, int available) {
        super("Requested " + requested + " but only " + available + " available");
        this.requested = requested;
        this.available = available;
    }

    public int getRequested() { return requested; }
    public int getAvailable() { return available; }
}
</code></pre>
<p>Adding fields for the domain values means the caller can inspect the exception programmatically. <code>InsufficientFundsException.getRequested()</code> returns a number your code can compare against a limit or display to a user. A generic <code>Exception("not enough funds")</code> forces the caller to parse the message string, which breaks the moment the message wording changes.</p>
<p>For unchecked exceptions that signal programming errors, extend <code>RuntimeException</code>:</p>
<pre><code class="language-java">public class InvalidAccountStateException extends RuntimeException {
    public InvalidAccountStateException(String message) {
        super(message);
    }

    public InvalidAccountStateException(String message, Throwable cause) {
        super(message, cause);
    }
}
</code></pre>
<p>Provide both constructors. Code that catches a lower-level exception and wants to re-throw it as <code>InvalidAccountStateException</code> needs the cause form. Code that detects the bad state directly uses the message-only form.</p>
<h2>The checked versus unchecked decision</h2>
<p>When designing an API method that can fail, the question is: can a reasonable caller recover from this failure?</p>
<p>If yes, use a checked exception. The compiler forces every caller to handle it or declare it. This is the right choice when the failure is a normal part of the interaction: <code>InsufficientFundsException</code>, <code>AccountLockedException</code>, <code>ParseException</code>. The caller chose to call <code>withdraw()</code> and must be prepared for the account to be short.</p>
<p>If no, use an unchecked exception. The failure is a programming error on the caller's side: a null argument where null is not allowed, an index out of range, an object that was used after it was closed. Requiring every caller to catch these exceptions creates noise without benefit. The right response to a programming error is to fix the calling code, not to surround every call with a <code>try-catch</code>.</p>
<p>A related test: if a checked exception type propagates through 10 methods and only one caller can meaningfully handle it, every intermediate method has to declare <code>throws YourException</code>. The declaration adds noise and couples those methods to your exception type. When you find yourself wrapping a checked exception in <code>RuntimeException</code> just to escape a <code>throws</code> chain, that is a signal the exception should have been unchecked in the first place.</p>
<h2>Common mistakes</h2>
<p><strong>Catching <code>Exception</code> or <code>Throwable</code> to suppress the error.</strong> This hides bugs and makes failures silent. If you catch <code>Throwable</code>, you catch <code>Error</code> too, including <code>OutOfMemoryError</code> and <code>StackOverflowError</code>. That almost never ends well. Catch the specific type you know how to handle.</p>
<p><strong>Empty catch blocks.</strong> A completely empty <code>catch</code> block eats the exception and leaves no trace. If you genuinely intend to swallow an exception, write a comment explaining why:</p>
<pre><code class="language-java">} catch (InterruptedException e) {
    Thread.currentThread().interrupt();  // restore interrupt status
}
</code></pre>
<p><strong>Swallowing while pretending to log.</strong> This pattern destroys the cause chain:</p>
<pre><code class="language-java">} catch (IOException e) {
    logger.error("Failed");  // no exception passed to logger
    throw new RuntimeException("Failed");  // no cause
}
</code></pre>
<p>Both the log entry and the re-thrown exception lose the original <code>IOException</code>. Pass the exception to the logger: <code>logger.error("Failed", e)</code>. Pass it to the constructor: <code>new RuntimeException("Failed", e)</code>.</p>
<p><strong>Using exceptions for control flow.</strong> Throwing an exception to signal "not found" in a search is expensive: the JVM captures the full stack trace on construction. Use <code>Optional&lt;T&gt;</code> or return <code>null</code> with a documented contract for "not found" cases. Reserve exceptions for genuinely exceptional conditions.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public static String findUser(Map&lt;String, String&gt; users, String id) {
    try {
        String name = users.get(id);
        return name.toUpperCase();
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
        return "unknown";
    }
}
</code></pre>
<p>Call this with a map that contains the key <code>"42"</code> mapping to <code>null</code>. What does <code>e.getMessage()</code> print? What does the method return? Then: why is catching <code>Exception</code> here a problem even though it "works" in this case?</p>
<p>The exception mechanism, the common types, and the design patterns together cover how Java programs signal and recover from failure. The next area in the curriculum is generics: how Java preserves type information across reusable components, and what erasure takes away.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Java&apos;s most common exceptions and what they mean</title>
      <link>https://unkletayo.dev/engineering/core-java/15-common-exceptions/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/15-common-exceptions/</guid>
      <description>What causes NullPointerException, ClassCastException, ArrayIndexOutOfBoundsException, IllegalArgumentException, StackOverflowError, and IOException, how to read a stack trace to find the source, and what each exception type tells you about the bug.</description>
      <pubDate>Tue, 08 Sep 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>exceptions</category>
      <category>debugging</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/15-common-exceptions.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/15-common-exceptions.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/15-common-exceptions.png" alt="Java&apos;s most common exceptions and what they mean" /></p>
<pre><code>Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "name" is null
	at com.example.UserService.formatName(UserService.java:24)
	at com.example.UserService.greet(UserService.java:18)
	at com.example.Main.main(Main.java:10)
</code></pre>
<p>You will read stack traces like this more than any other Java output. The class name tells you what happened. The message tells you which reference was null. The frames tell you exactly where.</p>
<p>Knowing what each exception type means lets you find the bug without reading every line of the program. This article covers the six you will encounter most often.</p>
<h2>How to read the stack trace</h2>
<p>Each indented line is one frame in the call stack at the moment the exception was thrown. The first frame is the site of the throw. The last frame is where the thread started, usually <code>main</code>.</p>
<pre><code>java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "name" is null
	at com.example.UserService.formatName(UserService.java:24)
	at com.example.UserService.greet(UserService.java:18)
	at com.example.Main.main(Main.java:10)
</code></pre>
<p>Start from the top. <code>UserService.java:24</code> is the line that threw. Open that file, go to line 24. If the class is yours, that is where you look first. If the top frame is inside a library class you did not write, move to the second frame, which is your code calling into that library.</p>
<p>The exception message refines the type. <code>NullPointerException</code> alone tells you something was null. The message "Cannot invoke <code>String.toUpperCase()</code> because <code>name</code> is null" tells you which variable was null and what you tried to do with it. Java 14 introduced helpful NullPointerException messages (JEP 358); on earlier versions you get just the type with no message.</p>
<p>A "Caused by:" section means the exception was wrapped:</p>
<pre><code>Exception in thread "main" com.example.DataAccessException: Failed to load user 42
	at com.example.UserRepository.findById(UserRepository.java:31)
	at com.example.UserService.getUser(UserService.java:19)
	at com.example.Main.main(Main.java:12)
Caused by: java.io.FileNotFoundException: /data/users/42.json (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
	at java.base/java.io.FileInputStream.&lt;init&gt;(FileInputStream.java:157)
	...
</code></pre>
<p>The <code>DataAccessException</code> is the outer exception. The <code>FileNotFoundException</code> is the cause, which is what actually failed. Read the "Caused by" chain from bottom to top: the original failure first, then each layer that caught and re-threw it.</p>
<h2>NullPointerException</h2>
<p>A reference variable holds an address. <code>null</code> means the variable holds no address. Calling a method or accessing a field on <code>null</code> throws <code>NullPointerException</code> because there is no object at the end of a null to operate on.</p>
<pre><code class="language-java">String name = null;
System.out.println(name.length());  // NullPointerException
</code></pre>
<p>The five common sources:</p>
<p><strong>1. A method returned null and you used the result without checking.</strong></p>
<pre><code class="language-java">String value = map.get("missingKey");  // returns null
System.out.println(value.trim());      // NPE
</code></pre>
<p><strong>2. A field was never initialized.</strong></p>
<pre><code class="language-java">public class Order {
    private List&lt;Item&gt; items;  // null until initialized

    public int total() {
        return items.stream().mapToInt(Item::price).sum();  // NPE
    }
}
</code></pre>
<p><strong>3. An array element was never assigned.</strong></p>
<pre><code class="language-java">String[] names = new String[3];  // all elements null
System.out.println(names[0].length());  // NPE
</code></pre>
<p><strong>4. Autoboxing a null <code>Integer</code> to <code>int</code>.</strong></p>
<pre><code class="language-java">Integer count = null;
int n = count;  // NullPointerException during unboxing
</code></pre>
<p><strong>5. A parameter that the caller expected to be non-null.</strong></p>
<p>The fix depends on the cause. If a method can legitimately return null, check before using the result. If it should never return null, that is a bug in that method. <code>Optional&lt;T&gt;</code> signals "this might be absent" in the return type, which forces the caller to handle the absent case explicitly rather than getting a surprise NPE at runtime.</p>
<h2>ArrayIndexOutOfBoundsException</h2>
<p>An array of length <code>n</code> has valid indices 0 through <code>n - 1</code>. Accessing index <code>n</code> or any negative index throws <code>ArrayIndexOutOfBoundsException</code>.</p>
<pre><code class="language-java">int[] scores = {90, 85, 72};
System.out.println(scores[3]);  // length is 3, valid indices are 0, 1, 2
</code></pre>
<pre><code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
</code></pre>
<p>The message gives both the index you used and the array's length. If the index equals the length, you are off by one. Check the loop condition: <code>i &lt; scores.length</code>, not <code>i &lt;= scores.length</code>.</p>
<p>The same error class applies to multi-dimensional arrays; each dimension is a separate array, so accessing <code>matrix[2][4]</code> can fail on either dimension independently.</p>
<h2>ClassCastException</h2>
<p>When you cast a reference to a type that the object is not an instance of, the JVM throws <code>ClassCastException</code>.</p>
<pre><code class="language-java">Object value = "hello";
Integer number = (Integer) value;  // ClassCastException
</code></pre>
<pre><code>Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer
</code></pre>
<p>The message names both the actual class and the class you tried to cast to. That pairing tells you exactly which cast failed. Look at the top frame to find the line.</p>
<p>The safe way to cast is to check first with <code>instanceof</code>, or use pattern matching (Java 16+):</p>
<pre><code class="language-java">// Before Java 16
if (value instanceof Integer) {
    Integer number = (Integer) value;
    System.out.println(number * 2);
}

// Java 16+ pattern matching
if (value instanceof Integer number) {
    System.out.println(number * 2);
}
</code></pre>
<p>Pattern matching eliminates the double lookup: the check and the cast happen in one operation, and the variable <code>number</code> is in scope and correctly typed inside the <code>if</code> block.</p>
<p><code>ClassCastException</code> appears frequently when working with raw collections (pre-generics, or when using external data like JSON), when unmarshalling heterogeneous data structures, and in legacy code that uses <code>Object</code> where a typed container would now serve better.</p>
<h2>IllegalArgumentException</h2>
<p><code>IllegalArgumentException</code> is an unchecked exception that signals the caller passed an invalid argument. It indicates a programming error on the caller's side.</p>
<pre><code class="language-java">public static double sqrt(double n) {
    if (n &lt; 0) {
        throw new IllegalArgumentException("Cannot take sqrt of negative: " + n);
    }
    return Math.sqrt(n);
}
</code></pre>
<p>The convention: throw it early, before doing any work, so the message points directly to the bad input. The message should include the invalid value, not just describe the constraint. "n must be non-negative (was -4.0)" is more useful than "invalid argument".</p>
<p>A related type is <code>IllegalStateException</code>, which signals that the method was called at the wrong time, not that the argument was wrong. Calling <code>iterator.remove()</code> before calling <code>iterator.next()</code> is an illegal state, not an illegal argument.</p>
<h2>StackOverflowError</h2>
<p>Every method call pushes a frame onto the call stack. The JVM limits the stack size (the default on HotSpot is roughly 512KB to 1MB per thread, depending on the platform; <code>-Xss</code> controls it). When the stack fills, the JVM throws <code>StackOverflowError</code>.</p>
<pre><code class="language-java">public static int factorial(int n) {
    return n * factorial(n - 1);  // no base case
}
</code></pre>
<pre><code>Exception in thread "main" java.lang.StackOverflowError
	at com.example.Main.factorial(Main.java:5)
	at com.example.Main.factorial(Main.java:5)
	at com.example.Main.factorial(Main.java:5)
	... (hundreds more identical frames)
</code></pre>
<p>The repeated identical frame is the tell. It is almost always a missing or unreachable base case in a recursive method.</p>
<p><code>StackOverflowError</code> is an <code>Error</code>, not an <code>Exception</code>. Do not catch it and continue. The stack is in an unrecoverable state once the error fires. Fix the recursion instead.</p>
<p>Mutual recursion is the less obvious variant: <code>methodA</code> calls <code>methodB</code>, which calls <code>methodA</code>, which calls <code>methodB</code>. The same repeated frames will appear, alternating between the two methods.</p>
<h2>IOException</h2>
<p><code>IOException</code> is the checked base class for I/O failures. It signals conditions that your code cannot prevent: a file that does not exist, a network that dropped, a disk that is full.</p>
<pre><code class="language-java">try {
    String content = Files.readString(Path.of("/data/config.json"));
} catch (IOException e) {
    System.err.println("Could not read config: " + e.getMessage());
}
</code></pre>
<p>The two most common subclasses:</p>
<p><code>FileNotFoundException</code> means the file path you provided does not point to an existing file. Check the path: a relative path resolves against the working directory of the Java process, which may not be where you expect when running from an IDE.</p>
<p><code>SocketTimeoutException</code> means a network operation waited longer than the configured timeout. The connection worked, but reading the response took too long. The timeout is a property of the socket or HTTP client configuration, not the exception type itself.</p>
<p>Since <code>IOException</code> is checked, the compiler forces you to handle it. That is intentional: file and network operations fail. Code that ignores the failure leaves the caller with no idea why subsequent operations produce garbage results.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public static int sum(List&lt;Integer&gt; values) {
    int total = 0;
    for (Integer v : values) {
        total += v;  // unboxing
    }
    return total;
}

List&lt;Integer&gt; withNull = new ArrayList&lt;&gt;();
withNull.add(10);
withNull.add(null);
withNull.add(5);

System.out.println(sum(withNull));
</code></pre>
<p>Which exception is thrown, and on which iteration? Then: what changes if you replace <code>List&lt;Integer&gt;</code> with <code>int[]</code>? The next article covers how to design your own exception types, when to use try-with-resources, and how to chain exceptions so the original cause is never lost. <a href="https://unkletayo.dev/engineering/core-java/16-exception-design/">Exception design: try-with-resources, chaining, and custom types</a> picks up from here.</p>
]]></content:encoded>
    </item>
    <item>
      <title>How Java separates interface from implementation</title>
      <link>https://unkletayo.dev/engineering/core-java/13-interfaces-and-abstract-classes/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/13-interfaces-and-abstract-classes/</guid>
      <description>What abstract classes and interfaces are, the specific things each can and cannot do, default methods since Java 8, sealed interfaces, functional interfaces as a bridge to lambdas, and a decision guide for choosing between them.</description>
      <pubDate>Tue, 25 Aug 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>oop</category>
      <category>interfaces</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/13-interfaces-and-abstract-classes.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/13-interfaces-and-abstract-classes.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/13-interfaces-and-abstract-classes.png" alt="How Java separates interface from implementation" /></p>
<p>A <code>SavingsAccount</code> and a <code>CheckingAccount</code> both need a <code>close()</code> operation. The behavior differs. One calculates final interest, the other clears overdraft protection. What they share is the guarantee that <code>close()</code> exists and can be called on any account type.</p>
<p>Java gives you two ways to express that guarantee: abstract classes and interfaces.</p>
<h2>Abstract classes</h2>
<p>An <strong>abstract class</strong> is a class that cannot be instantiated directly. It can declare abstract methods, methods with a signature but no body, that subclasses must implement.</p>
<pre><code class="language-java">public abstract class Account {
    protected final String id;
    protected int balance;

    protected Account(String id, int initialBalance) {
        this.id = id;
        this.balance = initialBalance;
    }

    public abstract void close();   // subclasses must implement this

    public void deposit(int amount) {
        if (amount &lt;= 0) throw new IllegalArgumentException("amount must be positive");
        balance += amount;
    }

    public int getBalance() { return balance; }
}
</code></pre>
<p><code>Account</code> provides shared state (<code>id</code>, <code>balance</code>), a shared constructor, and shared methods (<code>deposit</code>, <code>getBalance</code>). It declares <code>close()</code> as abstract, meaning: every concrete subclass must provide an implementation.</p>
<pre><code class="language-java">public class SavingsAccount extends Account {
    private double interestRate;

    public SavingsAccount(String id, int balance, double rate) {
        super(id, balance);
        this.interestRate = rate;
    }

    @Override
    public void close() {
        applyInterest();
        System.out.println("Savings account " + id + " closed with balance " + balance);
    }

    private void applyInterest() {
        balance += (int)(balance * interestRate);
    }
}
</code></pre>
<p>If a class extends an abstract class but does not implement every abstract method, it must itself be declared <code>abstract</code>.</p>
<h2>Interfaces</h2>
<p>An <strong>interface</strong> declares a contract: a set of method signatures that implementing classes agree to provide.</p>
<pre><code class="language-java">public interface Closeable {
    void close();
}

public interface Auditable {
    String auditTrail();
}
</code></pre>
<p>A class implements an interface with <code>implements</code>. It can implement multiple interfaces:</p>
<pre><code class="language-java">public class SavingsAccount extends Account implements Closeable, Auditable {

    @Override
    public void close() {
        // ...
    }

    @Override
    public String auditTrail() {
        return "Account " + id + ": " + balance;
    }
}
</code></pre>
<p>Before Java 8, interface methods were always abstract, with no implementation and no state. Since Java 8, interfaces can have <strong>default methods</strong> (a method body prefixed with <code>default</code>) and static methods.</p>
<pre><code class="language-java">public interface Closeable {
    void close();

    default boolean isClosed() {
        return false;   // subclasses can override or use this default
    }
}
</code></pre>
<p>Default methods exist so that methods can be added to widely-used interfaces without breaking every existing implementation. <code>java.util.Collection</code> gained <code>stream()</code> and <code>forEach()</code> as default methods in Java 8 without requiring all implementations to change.</p>
<p>Interfaces still cannot hold instance state. Interface fields are implicitly <code>public static final</code>. They are constants, not per-instance data.</p>
<h2>Multiple inheritance with interfaces</h2>
<p>A class can implement any number of interfaces. It can extend at most one class. This is Java's answer to multiple inheritance: you can share contracts freely across the type hierarchy, but you can only inherit implementation from one class at a time.</p>
<p>If two interfaces declare a default method with the same signature, the implementing class must override the method and choose which one to call (or provide its own):</p>
<pre><code class="language-java">interface A {
    default String name() { return "A"; }
}

interface B {
    default String name() { return "B"; }
}

class C implements A, B {
    @Override
    public String name() { return A.super.name(); }  // explicitly pick A's default
}
</code></pre>
<h2>Functional interfaces</h2>
<p>An interface with exactly one abstract method is a <strong>functional interface</strong>. Java 8 introduced the <code>@FunctionalInterface</code> annotation to signal intent and have the compiler enforce the one-method constraint.</p>
<pre><code class="language-java">@FunctionalInterface
public interface Validator&lt;T&gt; {
    boolean validate(T value);
}
</code></pre>
<p>Functional interfaces are the foundation for lambda expressions, covered in the functional programming articles. Any place that expects a <code>Validator&lt;Account&gt;</code> can accept a lambda <code>account -&gt; account.getBalance() &gt;= 0</code> without defining a named class.</p>
<p>The <code>java.util.function</code> package defines a standard library of functional interfaces: <code>Predicate&lt;T&gt;</code>, <code>Function&lt;T, R&gt;</code>, <code>Consumer&lt;T&gt;</code>, <code>Supplier&lt;T&gt;</code>, and their primitives and variations.</p>
<h2>Sealed interfaces and classes</h2>
<p>Java 17 introduced <strong>sealed</strong> types. A sealed class or interface restricts which classes may extend or implement it.</p>
<pre><code class="language-java">public sealed interface Shape permits Circle, Rectangle, Triangle {}

public record Circle(double radius) implements Shape {}
public record Rectangle(double width, double height) implements Shape {}
public record Triangle(double base, double height) implements Shape {}
</code></pre>
<p>The <code>permits</code> clause names the only allowed implementations. No other class can implement <code>Shape</code>. The compiler and reader both know that <code>Circle</code>, <code>Rectangle</code>, and <code>Triangle</code> are the complete set.</p>
<p>Sealed types pair well with pattern matching in <code>switch</code> expressions. The compiler can verify that a <code>switch</code> on a <code>Shape</code> covers all cases:</p>
<pre><code class="language-java">double area = switch (shape) {
    case Circle c    -&gt; Math.PI * c.radius() * c.radius();
    case Rectangle r -&gt; r.width() * r.height();
    case Triangle t  -&gt; 0.5 * t.base() * t.height();
};
</code></pre>
<p>No <code>default</code> case is needed. The compiler knows the three records are exhaustive.</p>
<h2>Choosing between abstract class and interface</h2>
<p>Both let you define a type that callers can program against. The difference comes down to what you need to share.</p>
<p>Use an <strong>abstract class</strong> when:</p>
<ul>
<li>Subclasses need to share state (fields)</li>
<li>Subclasses need to share constructor logic via <code>super()</code></li>
<li>Some methods have a common implementation that is not safe to make a default</li>
</ul>
<p>Use an <strong>interface</strong> when:</p>
<ul>
<li>You are defining a capability that unrelated classes can share (<code>Comparable</code>, <code>Iterable</code>, <code>Closeable</code>)</li>
<li>A class needs to satisfy multiple contracts simultaneously</li>
<li>You have no state to share</li>
</ul>
<p>If a class needs both shared state and multiple contracts, extend one abstract class and implement the remaining contracts as interfaces. That is the most common pattern in the Java standard library. <code>ArrayList</code>, for example, extends <code>AbstractList</code> (which provides shared list behaviour) and implements <code>List</code>, <code>RandomAccess</code>, <code>Cloneable</code>, and <code>Serializable</code>.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">interface Printable {
    void print();

    default String prefix() { return "[INFO]"; }
}

abstract class Document implements Printable {
    protected String content;

    Document(String content) { this.content = content; }

    @Override
    public String prefix() { return "[DOC]"; }
}

class Report extends Document {
    Report(String content) { super(content); }

    @Override
    public void print() {
        System.out.println(prefix() + " " + content);
    }
}

Printable p = new Report("Q3 results");
p.print();
</code></pre>
<p>Predict the output. Then: if you remove the <code>prefix()</code> override in <code>Document</code>, what changes?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Polymorphism and dynamic dispatch</title>
      <link>https://unkletayo.dev/engineering/core-java/12-polymorphism-and-dynamic-dispatch/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/12-polymorphism-and-dynamic-dispatch/</guid>
      <description>How Java selects the right method at runtime through dynamic dispatch, the vtable mechanism HotSpot uses, instanceof and pattern matching for type checks, and the ClassCastException trap.</description>
      <pubDate>Tue, 18 Aug 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>oop</category>
      <category>polymorphism</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/12-polymorphism-and-dynamic-dispatch.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/12-polymorphism-and-dynamic-dispatch.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/12-polymorphism-and-dynamic-dispatch.png" alt="Polymorphism and dynamic dispatch" /></p>
<pre><code class="language-java">Account a = new SavingsAccount("S001", 1000, 0.05);
System.out.println(a.getClass().getSimpleName());  // SavingsAccount
a.applyInterest();                                  // compile error
</code></pre>
<p>The variable <code>a</code> is declared as <code>Account</code>. The object it holds is a <code>SavingsAccount</code>. The JVM knows the runtime type; the compiler only knows the declared type. This distinction drives most of how objects behave in Java.</p>
<h2>Declared type versus runtime type</h2>
<p>A variable's <strong>declared type</strong> is what the compiler sees, the type in the declaration. A variable's <strong>runtime type</strong> is the actual class of the object it holds.</p>
<pre><code class="language-java">Account a = new SavingsAccount("S001", 1000, 0.05);
</code></pre>
<p>Declared type: <code>Account</code>. Runtime type: <code>SavingsAccount</code>.</p>
<p>The compiler uses the declared type to decide what methods and fields are accessible. <code>Account</code> does not declare <code>applyInterest()</code>, so the compiler rejects the call, even though the object is a <code>SavingsAccount</code>. The JVM uses the runtime type to decide which implementation of a method to invoke.</p>
<h2>Dynamic dispatch</h2>
<p>When you call an overridden method, Java always invokes the version that belongs to the runtime type.</p>
<pre><code class="language-java">Account[] accounts = {
    new Account("C001", 500),
    new SavingsAccount("S001", 1000, 0.05),
    new SavingsAccount("S002", 2000, 0.03)
};

for (Account a : accounts) {
    System.out.println(a.getBalance());
}
</code></pre>
<p>Every call <code>a.getBalance()</code> goes through the same declared type (<code>Account</code>) but each object knows its own class. If <code>SavingsAccount</code> overrides <code>getBalance()</code>, the overriding version runs for the savings accounts. If it does not override, the <code>Account</code> version runs. The loop does not need to know or check which type each element is.</p>
<p>This is called <strong>dynamic dispatch</strong> (or virtual dispatch): the method that runs is chosen at runtime based on the actual object, not at compile time based on the variable type. It enables code that operates on a declared type to work correctly with any subclass of that type.</p>
<h2>How HotSpot implements dispatch: the vtable</h2>
<p>As a HotSpot implementation detail (not a JLS guarantee): each class has a <strong>vtable</strong>, a table of method pointers with one entry per overridable method. When a subclass overrides a method, its vtable entry points to the overriding method. When the JVM calls a virtual method, it looks up the vtable of the object's actual class and jumps to the method there.</p>
<p>For <code>a.getBalance()</code> on a <code>SavingsAccount</code>, the JVM looks at the <code>SavingsAccount</code> vtable. If <code>SavingsAccount</code> overrides <code>getBalance</code>, the vtable entry points to that version; otherwise it points to <code>Account</code>'s version. The lookup takes essentially constant time.</p>
<p>JIT compilation replaces many vtable lookups with direct calls when the JIT can prove only one implementation is ever called at a given call site (monomorphic dispatch). The vtable mechanism is what makes the guarantee possible in the first place.</p>
<h2>instanceof and type checks</h2>
<p>Sometimes you need to know the runtime type explicitly, for example to call a method that the declared type does not expose.</p>
<p>The <code>instanceof</code> operator tests whether an object is an instance of a given class:</p>
<pre><code class="language-java">for (Account a : accounts) {
    if (a instanceof SavingsAccount) {
        SavingsAccount s = (SavingsAccount) a;
        s.applyInterest();
    }
}
</code></pre>
<p>Since Java 16, <strong>pattern matching for <code>instanceof</code></strong> combines the test and the cast into one statement:</p>
<pre><code class="language-java">for (Account a : accounts) {
    if (a instanceof SavingsAccount s) {
        s.applyInterest();
    }
}
</code></pre>
<p>If the test passes, <code>s</code> is bound to the object as a <code>SavingsAccount</code> and is available within the <code>if</code> block. The explicit cast is gone. The variable <code>s</code> is only in scope where the compiler can verify the test has passed.</p>
<h2>Casting</h2>
<p>A cast tells the compiler to treat a reference as a different type. The compiler trusts you; the JVM checks at runtime.</p>
<pre><code class="language-java">Account a = new Account("C001", 500);
SavingsAccount s = (SavingsAccount) a;  // compiles
// throws ClassCastException at runtime
</code></pre>
<p>The cast compiles because <code>Account</code> and <code>SavingsAccount</code> are related types. It throws <code>ClassCastException</code> at runtime because the actual object is not a <code>SavingsAccount</code>. Always use <code>instanceof</code> to guard a cast when the type is not certain.</p>
<p>A cast does not convert an object. It tells the JVM to interpret the reference as a different type. The object itself does not change.</p>
<h2>The design implication</h2>
<p>Dynamic dispatch is what makes it possible to write a <code>for</code> loop over <code>Account[]</code> without caring whether each element is a plain account, a savings account, or any future subclass. The loop calls the right method automatically. New subclasses can be added without changing the loop.</p>
<p>This only works when the subclass genuinely behaves like the superclass, meaning you can use a <code>SavingsAccount</code> wherever an <code>Account</code> is expected without breaking the caller's assumptions. That principle, that a subclass should be substitutable for its superclass, is what makes polymorphism useful rather than just surprising. <a href="https://unkletayo.dev/engineering/core-java/11-inheritance/">Inheritance</a> covers when that substitutability holds and when to prefer composition instead.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">class Shape {
    public double area() { return 0; }
}

class Circle extends Shape {
    double radius;
    Circle(double radius) { this.radius = radius; }

    @Override
    public double area() { return Math.PI * radius * radius; }
}

class Square extends Shape {
    double side;
    Square(double side) { this.side = side; }

    @Override
    public double area() { return side * side; }
}

Shape[] shapes = { new Circle(3), new Square(4), new Circle(1) };
double total = 0;
for (Shape s : shapes) {
    total += s.area();
}
System.out.printf("%.2f%n", total);
</code></pre>
<p>Predict the output. Then: if you add a new <code>Triangle</code> class that extends <code>Shape</code> and overrides <code>area()</code>, does the loop need to change?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Inheritance: extending a class</title>
      <link>https://unkletayo.dev/engineering/core-java/11-inheritance/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/11-inheritance/</guid>
      <description>What a subclass inherits from its superclass, how method overriding works, the role of super for fields and constructors, final classes and methods, and when to prefer composition over inheritance.</description>
      <pubDate>Tue, 11 Aug 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>oop</category>
      <category>inheritance</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/11-inheritance.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/11-inheritance.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/11-inheritance.png" alt="Inheritance: extending a class" /></p>
<p>Suppose you are building two account types: a standard account and a savings account. Both have an ID, a balance, deposit and withdraw operations. The savings account also accrues interest. Without inheritance, you either duplicate the shared code or pull it into a utility class.</p>
<p>Inheritance gives a third option: declare the shared behaviour once in a superclass and extend it.</p>
<h2>What extends means</h2>
<p>The <code>extends</code> keyword creates a subclass that inherits the accessible members of its superclass.</p>
<pre><code class="language-java">public class Account {
    protected final String id;
    protected int balance;

    public Account(String id, int initialBalance) {
        this.id = id;
        this.balance = initialBalance;
    }

    public void deposit(int amount) {
        if (amount &lt;= 0) throw new IllegalArgumentException("amount must be positive");
        balance += amount;
    }

    public void withdraw(int amount) {
        if (amount &lt;= 0) throw new IllegalArgumentException("amount must be positive");
        if (amount &gt; balance) throw new IllegalStateException("insufficient funds");
        balance -= amount;
    }

    public int getBalance() { return balance; }
}
</code></pre>
<pre><code class="language-java">public class SavingsAccount extends Account {
    private double interestRate;

    public SavingsAccount(String id, int initialBalance, double interestRate) {
        super(id, initialBalance);
        this.interestRate = interestRate;
    }

    public void applyInterest() {
        balance += (int)(balance * interestRate);
    }
}
</code></pre>
<p><code>SavingsAccount</code> inherits <code>deposit</code>, <code>withdraw</code>, and <code>getBalance</code> without redeclaring them. It adds <code>applyInterest</code>. Its constructor calls <code>super(id, initialBalance)</code> to initialize the fields declared in <code>Account</code>.</p>
<p>What a subclass inherits: all non-private fields and methods of its superclass. Private members exist in the superclass object but are not directly accessible from the subclass's code. The subclass can reach them only through the superclass's public or protected methods.</p>
<p>What a subclass does not inherit: constructors. Each class must declare its own constructors. A <code>super(...)</code> call invokes the superclass constructor, as covered in <a href="https://unkletayo.dev/engineering/core-java/09-initialization-order/">Initialization order</a>.</p>
<h2>Method overriding</h2>
<p>A subclass can replace a superclass method by declaring a method with the same name and parameter list. This is called overriding.</p>
<pre><code class="language-java">public class SavingsAccount extends Account {
    // ...

    @Override
    public void withdraw(int amount) {
        if (amount &gt; balance * 0.9) {
            throw new IllegalStateException("savings accounts require a 10% minimum balance");
        }
        super.withdraw(amount);
    }
}
</code></pre>
<p><code>@Override</code> is an annotation that tells the compiler you intend to override a superclass method. If the method signature doesn't match any superclass method, the compiler reports an error, a useful guard against typos like <code>widthdraw</code>.</p>
<p><code>super.withdraw(amount)</code> calls the superclass version. Without it, the overriding method would have to reimplement the amount check and balance update. With it, the subclass adds its rule and delegates the rest.</p>
<p>The return type of an overriding method can be a subtype of the superclass method's return type. This is called a covariant return type. If <code>Account.clone()</code> returned <code>Account</code>, <code>SavingsAccount.clone()</code> could return <code>SavingsAccount</code>.</p>
<h2>final: preventing extension and overriding</h2>
<p>Marking a class <code>final</code> prevents it from being subclassed. Marking a method <code>final</code> prevents it from being overridden.</p>
<pre><code class="language-java">public final class AccountId {
    private final String value;
    // ...
}
</code></pre>
<pre><code class="language-java">public class Account {
    public final String getId() { return id; }  // cannot be overridden
}
</code></pre>
<p><code>String</code> is a <code>final</code> class. No subclass can be created. This is part of what makes strings safe to use as map keys and cache entries: nothing can substitute a mutable <code>String</code>-like object in their place.</p>
<p>Use <code>final</code> when you need to guarantee that a class or method behaves exactly as written, with no possibility of a subclass changing that behaviour. The tradeoff is reduced extensibility.</p>
<h2>The Object superclass</h2>
<p>Every class in Java implicitly extends <code>java.lang.Object</code> if it has no explicit <code>extends</code> clause. <code>Object</code> provides default implementations of <code>equals()</code>, <code>hashCode()</code>, <code>toString()</code>, and a few other methods. This is why every Java object can be assigned to a variable of type <code>Object</code> and why every class has <code>hashCode()</code> without declaring it.</p>
<p><a href="https://unkletayo.dev/engineering/core-java/05-objects-equality-and-identity/">Objects, equality and identity</a> covers what <code>Object</code>'s default <code>equals()</code> and <code>hashCode()</code> do and why overriding them matters.</p>
<h2>Inheritance versus composition</h2>
<p>Inheritance models an "is-a" relationship: a <code>SavingsAccount</code> is an <code>Account</code>. Composition models a "has-a" relationship: an <code>Account</code> has a <code>TransactionLog</code>.</p>
<p>Inheritance is often overused. If a subclass overrides most of the superclass methods, or if the connection between the two classes is "shares some code" rather than a genuine type relationship, composition is usually cleaner.</p>
<pre><code class="language-java">// inheritance: SavingsAccount IS an Account
public class SavingsAccount extends Account { ... }

// composition: LimitedAccount HAS an Account
public class LimitedAccount {
    private final Account underlying;
    private final int dailyLimit;

    public void withdraw(int amount) {
        if (amount &gt; dailyLimit) throw new IllegalStateException("daily limit exceeded");
        underlying.withdraw(amount);
    }
}
</code></pre>
<p>With composition, <code>LimitedAccount</code> does not inherit the parts of <code>Account</code> it doesn't want. It delegates explicitly to what it needs and adds its own behaviour on top. Changes to <code>Account</code> that the <code>LimitedAccount</code> wasn't designed to handle won't silently affect it.</p>
<p>A rough guide: use inheritance when the subclass genuinely is a more specific version of the superclass type and can be used anywhere the superclass is expected. Use composition when you want to reuse behaviour without committing to that substitutability.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public class Base {
    public String describe() {
        return "Base";
    }
}

public class Child extends Base {
    @Override
    public String describe() {
        return super.describe() + " + Child";
    }
}

public class GrandChild extends Child {
    @Override
    public String describe() {
        return super.describe() + " + GrandChild";
    }
}

System.out.println(new GrandChild().describe());
</code></pre>
<p>Predict the output. Then: if you mark <code>Child.describe()</code> as <code>final</code>, what changes at compile time and what changes at runtime?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Encapsulation: hiding state behind a boundary</title>
      <link>https://unkletayo.dev/engineering/core-java/10-encapsulation-and-access-modifiers/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/10-encapsulation-and-access-modifiers/</guid>
      <description>What encapsulation is, the four Java access modifiers and what each permits, why the goal is protecting invariants rather than generating getters, and how records provide encapsulation for immutable data.</description>
      <pubDate>Tue, 04 Aug 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>oop</category>
      <category>encapsulation</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/10-encapsulation-and-access-modifiers.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/10-encapsulation-and-access-modifiers.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/10-encapsulation-and-access-modifiers.png" alt="Encapsulation: hiding state behind a boundary" /></p>
<pre><code class="language-java">public class Account {
    public int balance;
}

Account a = new Account();
a.balance = -500;
</code></pre>
<p>The compiler accepts this. Nothing stops any caller from putting the account into a state the class was never designed to handle. Encapsulation is the practice of preventing exactly this.</p>
<h2>What encapsulation protects</h2>
<p>In <a href="https://unkletayo.dev/engineering/core-java/08-classes-fields-constructors/">Classes, fields, and constructors</a>, we established that a constructor's job is to put an object into a valid initial state. Encapsulation extends that idea to the whole lifetime of the object. A valid <code>Account</code> has a non-negative balance. If <code>balance</code> is public, any code anywhere in the program can violate that invariant directly. If it is private, only <code>Account</code>'s own methods can touch it, so the invariant is only as fragile as those methods.</p>
<p>The goal is not to hide data for its own sake. The goal is to make it impossible to violate an invariant without going through code that checks the invariant first.</p>
<h2>The four access modifiers</h2>
<p>Java has four access levels, controlled by the keyword you put before a field, method, or constructor declaration.</p>
<p><strong><code>private</code></strong>: visible only within the declaring class. No other class, not even a subclass, can see it.</p>
<p><strong>Package-private (no keyword)</strong>: visible to all classes in the same package. This is the default when you write nothing.</p>
<p><strong><code>protected</code></strong>: visible within the same package and to subclasses in any package.</p>
<p><strong><code>public</code></strong>: visible everywhere.</p>
<pre><code class="language-java">public class Account {
    private int balance;          // only Account can read or write this
    int transactionCount;         // package-private: visible to Account and classes in its package
    protected String ownerId;     // visible to Account, its package, and subclasses
    public String id;             // visible everywhere
}
</code></pre>
<p>A good default for fields: <code>private</code>. Expose state only through methods that can enforce the invariants.</p>
<h2>Methods as the controlled entry point</h2>
<p>A private field with a public method gives the class control over every change to that field:</p>
<pre><code class="language-java">public class Account {
    private int balance;

    Account(String id, int initialBalance) {
        if (initialBalance &lt; 0) throw new IllegalArgumentException("balance cannot be negative");
        this.balance = initialBalance;
    }

    public void deposit(int amount) {
        if (amount &lt;= 0) throw new IllegalArgumentException("deposit amount must be positive");
        this.balance += amount;
    }

    public void withdraw(int amount) {
        if (amount &lt;= 0) throw new IllegalArgumentException("amount must be positive");
        if (amount &gt; this.balance) throw new IllegalStateException("insufficient funds");
        this.balance -= amount;
    }

    public int getBalance() {
        return this.balance;
    }
}
</code></pre>
<p>Now every path that changes <code>balance</code> goes through a check. No external code can set the balance to -500. The class's invariants hold as long as its methods are correct, and you only have to audit those methods, not every caller.</p>
<h2>When getters and setters are not enough</h2>
<p>A common mistake is to declare every field private and then generate a getter and setter for each one. That is not encapsulation. It is a private field with a public field hidden behind two method calls.</p>
<pre><code class="language-java">// this exposes balance exactly as much as a public field would
public void setBalance(int balance) {
    this.balance = balance;
}
</code></pre>
<p>A setter with no logic is the same as a public field. The point of encapsulation is that the method enforces constraints. If <code>setBalance</code> does nothing but assign, any caller can still put the account into an invalid state.</p>
<p>Write methods that describe operations, <code>deposit</code>, <code>withdraw</code>, <code>close</code>, not methods that expose the internal slot. Sometimes a getter is appropriate for read access. A setter is appropriate only when unrestricted write access is genuinely part of the contract.</p>
<h2>Immutable objects and records</h2>
<p>The strongest encapsulation is immutability: a class whose state cannot change after construction. An immutable object can safely be shared across threads, used as a map key, and cached without coordination.</p>
<p>Before Java 16, writing an immutable value type required declaring all fields <code>private final</code>, writing a constructor that sets them, and providing only getter methods. Java 16 introduced <strong>records</strong> as a compact syntax for exactly this pattern.</p>
<pre><code class="language-java">public record Point(int x, int y) {}
</code></pre>
<p>The compiler generates:</p>
<ul>
<li>A constructor that takes <code>x</code> and <code>y</code></li>
<li>Private final fields <code>x</code> and <code>y</code></li>
<li>Accessor methods <code>x()</code> and <code>y()</code> (not <code>getX()</code>)</li>
<li><code>equals()</code>, <code>hashCode()</code>, and <code>toString()</code> based on all components</li>
</ul>
<p>Records cannot have mutable state. Their fields are always <code>private final</code>. You cannot add a setter. Use a record when the entire point of the class is to hold a fixed set of values, such as a coordinate, a range, or a result with a status and a value.</p>
<pre><code class="language-java">public record TransferResult(boolean success, String reason) {}

TransferResult result = new TransferResult(false, "insufficient funds");
System.out.println(result.success());   // false
System.out.println(result.reason());    // insufficient funds
</code></pre>
<h2>Packages as a second boundary</h2>
<p>The package-private level (no keyword) gives you a boundary that is wider than a single class but narrower than the whole program. Classes in the same package can share implementation details without exposing them to the rest of the codebase.</p>
<p>A common use: a public class with package-private helper classes. The helper classes are visible to the main class and to tests in the same package, but not to callers outside the package.</p>
<p>Packages are not a security boundary. Any code can be placed in any package. They are an organizational boundary that communicates intent and limits accidental coupling.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public class Counter {
    private int count = 0;

    public void increment() { count++; }
    public void decrement() { count--; }
    public int value() { return count; }
}
</code></pre>
<p>Can <code>count</code> ever go negative? If yes, what change would prevent it? If you converted <code>Counter</code> to a record, what would you lose and what would you gain?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Initialization order: when each line of code runs</title>
      <link>https://unkletayo.dev/engineering/core-java/09-initialization-order/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/09-initialization-order/</guid>
      <description>When static initializers run versus instance initializers, how this() and super() chain constructors together, and the exact sequence Java follows from class loading to a fully constructed object.</description>
      <pubDate>Tue, 28 Jul 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>oop</category>
      <category>constructors</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/09-initialization-order.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/09-initialization-order.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/09-initialization-order.png" alt="Initialization order: when each line of code runs" /></p>
<pre><code class="language-java">class Tracker {
    static int instances = 0;

    static {
        instances = 100;
    }

    int id;

    {
        id = ++instances;
    }

    Tracker() {
        System.out.println("id=" + id + ", total=" + instances);
    }
}

new Tracker();
new Tracker();
</code></pre>
<p>What prints? The answer depends on when each block runs relative to the others. This article explains the sequence.</p>
<h2>Two categories of initialization</h2>
<p>Java splits initialization into two categories: class initialization and instance initialization.</p>
<p><strong>Class initialization</strong> happens once per class, the first time the JVM uses it. It runs static field initializers and static initializer blocks in textual order.</p>
<p><strong>Instance initialization</strong> happens once per object, every time <code>new</code> is called. It runs instance field initializers, instance initializer blocks, and the constructor body.</p>
<p>The two categories never overlap for the same execution. Static code runs before any instance is created. Instance code runs after static code has already finished.</p>
<h2>Class initialization</h2>
<p>The JVM initializes a class the first time it is actively used: when an instance is created, a static method is called, a static field is accessed, or the class appears as the left-hand side of an assignment. It does not initialize a class just because the classloader found it.</p>
<p>During class initialization, static field initializers and <code>static { }</code> blocks run in textual order:</p>
<pre><code class="language-java">class Config {
    static int maxConnections = 10;         // runs first

    static {
        System.out.println("class loaded"); // runs second
        maxConnections = 20;                // overwrites the field initializer
    }

    static int timeout = maxConnections * 2; // runs third, sees 20
}
</code></pre>
<p>After this class initializes: <code>maxConnections</code> is 20, <code>timeout</code> is 40.</p>
<p>Class initialization happens exactly once. If two threads try to initialize the same class simultaneously, the JVM serializes them: the second thread waits until the first finishes. This is a language guarantee (JLS §12.4.2).</p>
<h2>Instance initialization</h2>
<p>When <code>new</code> creates an object, the JVM runs three things in order:</p>
<ol>
<li>The superclass constructor (covered below under <code>super()</code>)</li>
<li>Instance field initializers and instance initializer blocks, in textual order</li>
<li>The rest of the constructor body</li>
</ol>
<p>An <strong>instance initializer</strong> is a bare <code>{ }</code> block inside the class body but outside any method or constructor. It is copied into every constructor by the compiler, after any <code>super()</code> call and before the constructor's own statements.</p>
<pre><code class="language-java">class Counter {
    int count = 0;      // field initializer

    {
        count = 10;     // instance initializer — overwrites 0
    }

    Counter() {
        count = 20;     // constructor body — overwrites 10
    }
}
</code></pre>
<p>After <code>new Counter()</code>: <code>count</code> is 20. The field initializer sets 0, the instance initializer overwrites with 10, then the constructor body overwrites with 20.</p>
<p>That example is contrived. You would not normally use all three. Instance initializers are useful when you want shared setup code across multiple constructors without calling a helper method, or when initializing an anonymous class.</p>
<h2>Constructor chaining with this()</h2>
<p><a href="https://unkletayo.dev/engineering/core-java/08-classes-fields-constructors/">Classes, fields, and constructors</a> introduced the <code>this(...)</code> call. When a constructor starts with <code>this(args)</code>, it delegates immediately to another constructor in the same class. That constructor runs first. When it returns, nothing else in the calling constructor runs before it. The <code>this()</code> call must be the first statement.</p>
<pre><code class="language-java">class Account {
    String id;
    int balance;
    boolean active;

    Account(String id) {
        this(id, 0);        // calls Account(String, int) first
        // this line runs after Account(String, int) returns
    }

    Account(String id, int balance) {
        this.id = id;
        this.balance = balance;
        this.active = true;
    }
}
</code></pre>
<p>The chain terminates at a constructor that does not start with <code>this()</code>. That terminal constructor is responsible for calling <code>super()</code>.</p>
<p>You cannot have both <code>this()</code> and <code>super()</code> in the same constructor. <code>this()</code> transfers the obligation to call <code>super()</code> to the constructor it delegates to.</p>
<h2>super() and the constructor chain up the hierarchy</h2>
<p>Every constructor either starts with <code>this(args)</code> or starts with <code>super(args)</code>. If you write neither, the compiler inserts <code>super()</code> automatically.</p>
<p><code>super()</code> invokes the superclass constructor. Because every class extends <code>Object</code> (explicitly or implicitly), every constructor chain eventually calls <code>Object()</code>. The superclass constructor runs before the subclass's instance initializers and constructor body.</p>
<p>For a class hierarchy <code>A</code> extends <code>Object</code>, <code>B</code> extends <code>A</code>, the sequence when calling <code>new B()</code> is:</p>
<ol>
<li><code>B()</code>'s first statement is <code>super()</code> (explicit or implicit), so <code>A()</code> runs first</li>
<li><code>A()</code>'s first statement is <code>super()</code>, so <code>Object()</code> runs first</li>
<li><code>Object()</code> returns</li>
<li><code>A()</code>'s instance initializers and field initializers run (in textual order)</li>
<li><code>A()</code>'s constructor body runs</li>
<li><code>A()</code> returns</li>
<li><code>B()</code>'s instance initializers and field initializers run</li>
<li><code>B()</code>'s constructor body runs</li>
</ol>
<pre><code class="language-java">class Animal {
    String type;

    Animal(String type) {
        this.type = type;
        System.out.println("Animal: " + type);
    }
}

class Dog extends Animal {
    String name;

    Dog(String name) {
        super("dog");                   // must come first
        this.name = name;
        System.out.println("Dog: " + name);
    }
}

new Dog("Rex");
</code></pre>
<p>Output:</p>
<pre><code>Animal: dog
Dog: Rex
</code></pre>
<p>The superclass constructor finishes before the subclass constructor continues. <code>this.name = name</code> does not run until after <code>Animal(String)</code> has returned.</p>
<p>If a superclass has no no-argument constructor, every subclass constructor must include an explicit <code>super(args)</code> call. The compiler cannot generate one, because it doesn't know what arguments to pass.</p>
<h2>The full sequence</h2>
<p>Putting it together, here is the complete sequence for <code>new Tracker()</code> from the opening:</p>
<ol>
<li>The <code>Tracker</code> class has not been used yet, so class initialization runs first:
<ul>
<li><code>static int instances = 0</code> runs (instances = 0)</li>
<li><code>static { instances = 100; }</code> runs (instances = 100)</li>
</ul>
</li>
<li>Instance creation for the first <code>new Tracker()</code>:
<ul>
<li>Memory is allocated; <code>id</code> is set to its default value 0</li>
<li><code>super()</code> runs (Object's constructor, which does nothing visible)</li>
<li>Instance field initializers and instance initializers run in textual order:
<ul>
<li><code>int id</code> has no explicit initializer; it was already 0 from the default</li>
<li><code>{ id = ++instances; }</code> runs: <code>instances</code> becomes 101, <code>id</code> is set to 101</li>
</ul>
</li>
<li>Constructor body: <code>System.out.println("id=101, total=101")</code></li>
</ul>
</li>
<li>Instance creation for the second <code>new Tracker()</code>:
<ul>
<li>Class initialization does not repeat</li>
<li>Memory allocated, <code>id</code> defaults to 0</li>
<li><code>super()</code> runs</li>
<li><code>{ id = ++instances; }</code> runs: <code>instances</code> becomes 102, <code>id</code> is 102</li>
<li>Constructor body: <code>System.out.println("id=102, total=102")</code></li>
</ul>
</li>
</ol>
<p>The output is:</p>
<pre><code>id=101, total=101
id=102, total=102
</code></pre>
<h2>A caution on calling overridable methods from constructors</h2>
<p>The initialization sequence explains a classic trap. A superclass constructor runs before the subclass's instance initializers, so subclass fields are still at their default values when the superclass constructor body executes. If the superclass constructor calls a method that is overridden in the subclass, and that override reads a subclass field, it reads the default value, not the initialized value.</p>
<pre><code class="language-java">class Base {
    Base() {
        printValue();   // calls the overridden version
    }

    void printValue() {
        System.out.println("Base");
    }
}

class Child extends Base {
    int value = 42;

    @Override
    void printValue() {
        System.out.println(value);  // value is 0 here, not 42
    }
}

new Child();  // prints 0
</code></pre>
<p><code>value = 42</code> has not run yet when <code>Base()</code> calls <code>printValue()</code>. It runs after <code>Base()</code> returns. Keep constructors simple: assign fields, validate arguments, call <code>this()</code> or <code>super()</code>, but avoid calling overridable methods from a constructor.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">class Widget {
    static int count = 0;
    int serial;

    static {
        count = 10;
    }

    {
        serial = ++count;
    }

    Widget() {}

    Widget(int serial) {
        this();
        this.serial = serial;
    }
}

Widget a = new Widget();
Widget b = new Widget(99);
System.out.println(a.serial + " / " + b.serial + " / " + Widget.count);
</code></pre>
<p>Predict the output. Consider: when does the static block run, what does the instance initializer do in each case, and how does <code>this()</code> in the second constructor affect the order?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Classes: fields, constructors, and defaults</title>
      <link>https://unkletayo.dev/engineering/core-java/08-classes-fields-constructors/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/08-classes-fields-constructors/</guid>
      <description>What fields hold and how they get default values, what constructors do that methods cannot, when Java provides a no-argument constructor, constructor overloading, and the invariant that every constructor&apos;s job is to establish.</description>
      <pubDate>Tue, 21 Jul 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>oop</category>
      <category>classes</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/08-classes-fields-constructors.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/08-classes-fields-constructors.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/08-classes-fields-constructors.png" alt="Classes: fields, constructors, and defaults" /></p>
<pre><code class="language-java">public class Counter {
    int count;
    boolean active;
    String label;
}

Counter c = new Counter();
System.out.println(c.count);   // 0
System.out.println(c.active);  // false
System.out.println(c.label);   // null
</code></pre>
<p>We never set those fields. Where did <code>0</code>, <code>false</code>, and <code>null</code> come from?</p>
<h2>What a class declaration contains</h2>
<p>A class declaration describes a template for objects. Each object created from that template gets its own copy of the instance state the class declares.</p>
<p>A class body can contain four kinds of members:</p>
<p><strong>Fields</strong> describe the state an object holds. <code>int count</code> says every <code>Counter</code> object has a slot named <code>count</code> that holds an <code>int</code>.</p>
<p><strong>Constructors</strong> run when a new object is created. Their job is to put the object into a valid initial state.</p>
<p><strong>Methods</strong> define the operations the object supports.</p>
<p><strong>Nested types</strong>, inner classes, static nested classes, and so on, are covered in a later article.</p>
<p>Fields and constructors are the focus here.</p>
<h2>Fields and their default values</h2>
<p>A field declaration gives each instance a named slot to hold a value. The type determines what values are allowed and how much space the slot occupies.</p>
<pre><code class="language-java">public class Account {
    String id;          // reference to a String
    int balance;        // 32-bit integer
    boolean active;     // true or false
    double rate;        // 64-bit floating-point
}
</code></pre>
<p>Before a constructor runs, the JVM allocates memory for the new object and sets each field to its <strong>default value</strong>. The JLS (§4.12.5) defines defaults for every type:</p>
<table>
<thead>
<tr>
<th>Type</th>
<th>Default value</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code></td>
<td><code>0</code></td>
</tr>
<tr>
<td><code>float</code></td>
<td><code>0.0f</code></td>
</tr>
<tr>
<td><code>double</code></td>
<td><code>0.0d</code></td>
</tr>
<tr>
<td><code>char</code></td>
<td><code>'\u0000'</code> (the null character)</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>false</code></td>
</tr>
<tr>
<td>Any reference type</td>
<td><code>null</code></td>
</tr>
</tbody>
</table>
<p>This is why <code>c.count</code> was <code>0</code> and <code>c.label</code> was <code>null</code> in the opening example. The JVM set them before any constructor ran.</p>
<p>Default values exist so that every field has a defined value from the moment the object is allocated. Code that reads a field can always rely on getting a value, not uninitialized memory.</p>
<p>You can supply an explicit initial value directly in the declaration:</p>
<pre><code class="language-java">public class Account {
    String id;
    int balance = 0;         // explicit, matches the default
    boolean active = true;   // different from the default
    double rate = 0.05;
}
</code></pre>
<p>Field initializers like <code>active = true</code> run after the JVM's default-value pass and before the constructor body. <a href="https://unkletayo.dev/engineering/core-java/09-initialization-order/">Initialization order</a> covers the full sequence, including static initializers and instance initializer blocks.</p>
<h2>Constructors</h2>
<p>A constructor is a block of code that runs when <code>new</code> creates an object. It looks like a method but has no return type and must be named after the class.</p>
<pre><code class="language-java">public class Account {
    String id;
    int balance;
    boolean active;

    Account(String id, int balance) {
        this.id = id;
        this.balance = balance;
        this.active = true;
    }
}
</code></pre>
<p><code>this.id</code> refers to the field. <code>id</code> without <code>this</code> refers to the parameter. When a parameter name shadows a field name, <code>this</code> distinguishes them.</p>
<p>What makes a constructor different from a method? A constructor runs exactly once per object, at creation time, and receives the newly allocated object as <code>this</code>. The constructor's job is to put that object into a valid state before any method can be called on it.</p>
<p>An <code>Account</code> with a negative balance or a null ID might violate invariants that the rest of the code depends on. The constructor is the right place to enforce those constraints:</p>
<pre><code class="language-java">Account(String id, int initialBalance) {
    if (id == null || id.isEmpty()) throw new IllegalArgumentException("id required");
    if (initialBalance &lt; 0) throw new IllegalArgumentException("balance cannot be negative");
    this.id = id;
    this.balance = initialBalance;
    this.active = true;
}
</code></pre>
<p>If the constructor throws, the <code>new</code> expression throws and no object is returned. The partially constructed object is not reachable from the caller's perspective.</p>
<h2>The default constructor</h2>
<p>If a class has no declared constructor, the Java compiler generates a <strong>default constructor</strong>: a public no-argument constructor that calls <code>super()</code> and does nothing else.</p>
<pre><code class="language-java">// source code
public class Counter {
    int count;
}

// what the compiler generates (not visible in source)
public Counter() {
    super();
}
</code></pre>
<p>The moment you declare any constructor, the compiler stops generating the default. If you declare a one-argument constructor and also want a no-argument constructor, you must write both explicitly.</p>
<pre><code class="language-java">public class Account {
    String id;
    int balance;

    Account(String id, int balance) {
        this.id = id;
        this.balance = balance;
    }

    // no default constructor generated — Account() { } would be a compile error
}

Account a = new Account();  // compile error: no suitable constructor found
</code></pre>
<p>This is a common source of confusion when adding a first constructor to an existing class: callers that relied on the default constructor break.</p>
<h2>Constructor overloading</h2>
<p>A class can have multiple constructors, as long as their parameter lists differ in type, number, or order. The compiler picks the matching constructor based on the argument types at the call site.</p>
<pre><code class="language-java">public class Account {
    String id;
    int balance;
    boolean active;

    Account(String id) {
        this.id = id;
        this.balance = 0;
        this.active = true;
    }

    Account(String id, int initialBalance) {
        this.id = id;
        this.balance = initialBalance;
        this.active = true;
    }
}
</code></pre>
<p>Both constructors work, but they repeat the assignment <code>this.active = true</code>. When constructors share setup logic, <code>this(...)</code> delegates to another constructor in the same class:</p>
<pre><code class="language-java">Account(String id) {
    this(id, 0);        // delegates to Account(String, int)
}

Account(String id, int initialBalance) {
    if (id == null || id.isEmpty()) throw new IllegalArgumentException("id required");
    if (initialBalance &lt; 0) throw new IllegalArgumentException("balance cannot be negative");
    this.id = id;
    this.balance = initialBalance;
    this.active = true;
}
</code></pre>
<p><code>this(id, 0)</code> must be the <strong>first statement</strong> in the constructor. Only one constructor does the real work; the others delegate to it. <a href="https://unkletayo.dev/engineering/core-java/09-initialization-order/">Initialization order</a> covers what happens step by step when <code>this()</code> and <code>super()</code> chain together.</p>
<h2>Establishing invariants</h2>
<p>An <strong>invariant</strong> is a condition that must hold for all objects of a class. For <code>Account</code>, the invariants might be: <code>id</code> is never null, <code>balance</code> is never negative, <code>active</code> is always set to something meaningful.</p>
<p>The constructor is the only place where you can guarantee an invariant holds from the moment an object exists. Once an object escapes the constructor, callers can invoke any public method, so the invariants need to be maintained by those methods too, but they start from a valid state if the constructor did its job.</p>
<p>Separating valid-state enforcement (constructor) from operation logic (methods) keeps each piece of code focused.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public class Sensor {
    String location;
    double reading = -1.0;
    boolean calibrated;

    Sensor(String location) {
        this.location = location;
        this.calibrated = true;
    }
}

Sensor s = new Sensor("room-1");
</code></pre>
<p>What are the values of <code>s.location</code>, <code>s.reading</code>, and <code>s.calibrated</code> after construction? If you remove the constructor and call <code>new Sensor()</code> instead, what are the three field values?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Strings: building, joining, and formatting</title>
      <link>https://unkletayo.dev/engineering/core-java/07-strings-building-joining-formatting/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/07-strings-building-joining-formatting/</guid>
      <description>String concatenation under the hood, why the loop pattern is expensive, StringBuilder versus StringBuffer, StringJoiner and String.join(), formatted() versus format(), and a decision guide for picking the right tool.</description>
      <pubDate>Tue, 14 Jul 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>strings</category>
      <category>stringbuilder</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/07-strings-building-joining-formatting.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/07-strings-building-joining-formatting.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/07-strings-building-joining-formatting.png" alt="Strings: building, joining, and formatting" /></p>
<p>String concatenation with <code>+</code> is fine for joining two or three values. In a loop, it becomes expensive quickly. Here is why.</p>
<pre><code class="language-java">String report = "";
for (String line : lines) {
    report = report + line + "\n";
}
</code></pre>
<p>Each iteration creates a new <code>String</code> object from the entire accumulated text so far, plus one more line. After the first iteration, <code>report</code> holds one line. After the second, two. The JVM allocated a fresh string for each step. For a list of <em>n</em> lines of average length <em>L</em>, the total bytes allocated across all iterations are <em>L</em> × (1 + 2 + 3 + ... + <em>n</em>) = <em>L</em> × <em>n</em>(<em>n</em>+1)/2. That grows with the square of the input size.</p>
<p>This article covers when <code>+</code> is appropriate, what to use instead when it is not, and how to choose among <code>StringBuilder</code>, <code>StringBuffer</code>, <code>StringJoiner</code>, and <code>formatted()</code>.</p>
<h2>How + works</h2>
<p>The <code>+</code> operator on strings is not a built-in JVM instruction. The compiler translates it. Since Java 9 (JEP 280), the translation uses an <code>invokedynamic</code> instruction that calls <code>StringConcatFactory.makeConcatWithConstants()</code> at runtime. The runtime can choose the concatenation strategy; the common path allocates a single internal buffer for each <code>+</code> expression and produces one result string.</p>
<p>For a single concatenation expression, one call site, that one-buffer-one-result behavior is fine.</p>
<pre><code class="language-java">String greeting = "Hello, " + name + "!";  // one expression, one result
</code></pre>
<p>The expensive case is a loop where each iteration assigns the full result back to an accumulator. Each assignment creates a new string containing the entire accumulated text, so the next iteration must copy all of it again, plus one more element.</p>
<pre><code class="language-java">for (String item : items) {
    result = result + item + ", ";  // full copy every iteration
}
</code></pre>
<p>The fix is a mutable buffer that accumulates content without copying, then produces one string at the end.</p>
<h2>StringBuilder</h2>
<p><code>StringBuilder</code> builds a string by accumulating content in a mutable internal buffer, then producing the final <code>String</code> with a single <code>toString()</code> call.</p>
<pre><code class="language-java">StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append(line).append('\n');
}
String report = sb.toString();
</code></pre>
<p>The JVM allocates the buffer once, with an initial capacity of 16 characters. When the content exceeds the capacity, it expands to <code>(oldCapacity + 1) × 2</code>, which is 34 for the initial 16-character buffer. The final <code>toString()</code> allocates exactly one <code>String</code> of the right size. Total allocations: one buffer (possibly reallocated a handful of times), one result string, constant regardless of input size.</p>
<p>If you know the expected length in advance, pass it to the constructor:</p>
<pre><code class="language-java">int estimated = lines.size() * 80;
StringBuilder sb = new StringBuilder(estimated);
</code></pre>
<p>This eliminates reallocations. The estimate does not need to be exact; it just prevents the repeated doubling that happens with large inputs and a 16-character starting capacity.</p>
<p>The methods you reach for most are <code>append()</code>, <code>insert(int offset, String str)</code>, <code>delete(int start, int end)</code>, <code>deleteCharAt(int index)</code>, <code>reverse()</code>, <code>charAt(int index)</code>, <code>setCharAt(int index, char ch)</code>, <code>indexOf(String str)</code>, <code>substring(int start, int end)</code>, and <code>toString()</code>. Most mutating methods return <code>this</code>, so appends can chain:</p>
<pre><code class="language-java">sb.append("Account ").append(id).append(": ").append(balance);
</code></pre>
<p>One thing worth knowing: <code>sb.toString()</code> creates a new <code>String</code> from the buffer contents but does not reset the builder. Calling <code>toString()</code> twice gives two separate <code>String</code> objects with equal content. If you need to reuse the builder, call <code>sb.setLength(0)</code> to clear it.</p>
<p><code>StringBuilder</code> is not thread-safe. That is deliberate. Its single-threaded use case does not need synchronization.</p>
<h2>StringBuffer</h2>
<p><code>StringBuffer</code> has the same API as <code>StringBuilder</code>. Every method is <code>synchronized</code>.</p>
<p>If two threads must append to the same builder simultaneously, <code>StringBuffer</code> prevents data races. In practice this scenario is unusual in well-structured code. Strings passed between threads are usually immutable <code>String</code> objects, not shared mutable builders.</p>
<p>For single-threaded code, prefer <code>StringBuilder</code>. Its methods are identical, without the synchronization cost.</p>
<p><code>StringBuffer</code> predates <code>StringBuilder</code> by several Java versions. <code>StringBuilder</code> was added in Java 5 specifically for single-threaded use. New code rarely needs <code>StringBuffer</code>.</p>
<h2>StringJoiner</h2>
<p><code>StringJoiner</code> builds a delimiter-separated sequence, with optional prefix and suffix.</p>
<pre><code class="language-java">StringJoiner sj = new StringJoiner(", ");
sj.add("Alice").add("Bob").add("Carol");
System.out.println(sj);  // Alice, Bob, Carol
</code></pre>
<p>With a prefix and suffix:</p>
<pre><code class="language-java">StringJoiner sj = new StringJoiner(", ", "[", "]");
sj.add("Alice").add("Bob");
System.out.println(sj);  // [Alice, Bob]
</code></pre>
<p>Before any element is added, <code>toString()</code> returns an empty string, with no prefix, no suffix, and no delimiter. Use <code>setEmptyValue()</code> if you need a different result for the empty case:</p>
<pre><code class="language-java">StringJoiner sj = new StringJoiner(", ", "[", "]");
sj.setEmptyValue("none");
System.out.println(sj);   // none
sj.add("A001");
System.out.println(sj);   // [A001]
</code></pre>
<p><code>merge(StringJoiner other)</code> appends <code>other</code>'s accumulated content, without its prefix and suffix, as a single unit to the current joiner. The API documentation states: "elements from the other StringJoiner are concatenated with that delimiter and the result is appended to this StringJoiner as a single element." So <code>other</code>'s internal delimiter is preserved for the transferred content, and the primary joiner's delimiter separates that content from earlier elements.</p>
<pre><code class="language-java">StringJoiner primary = new StringJoiner(", ", "(", ")");
primary.add("x");

StringJoiner secondary = new StringJoiner("-", "{", "}");
secondary.add("y").add("z");

primary.merge(secondary);
System.out.println(primary);  // (x, y-z)
</code></pre>
<p>The <code>{</code> and <code>}</code> from <code>secondary</code> do not appear. The <code>y</code> and <code>z</code> were joined using <code>secondary</code>'s <code>-</code> delimiter, producing the unit <code>y-z</code>. That unit was appended to <code>primary</code>, which then joins <code>x</code> and <code>y-z</code> with its own <code>, </code> delimiter. If <code>other</code> has no elements, <code>merge()</code> has no effect.</p>
<p><code>String.join()</code> delegates to <code>StringJoiner</code> internally. When you have a list and want a joined string in one step, <code>String.join()</code> is simpler. When you need to build incrementally, control the prefix and suffix, or compose a stream with <code>Collectors.joining()</code>, use <code>StringJoiner</code> directly.</p>
<h2>Common String operations</h2>
<p>A reference table of the methods you use most.</p>
<p><strong>Inspection</strong></p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Returns</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>length()</code></td>
<td><code>int</code></td>
<td>Character count</td>
</tr>
<tr>
<td><code>isEmpty()</code></td>
<td><code>boolean</code></td>
<td>True if length is 0</td>
</tr>
<tr>
<td><code>isBlank()</code></td>
<td><code>boolean</code></td>
<td>True if empty or all Unicode whitespace (Java 11)</td>
</tr>
<tr>
<td><code>charAt(int index)</code></td>
<td><code>char</code></td>
<td>Throws <code>IndexOutOfBoundsException</code> if out of range</td>
</tr>
<tr>
<td><code>indexOf(String str)</code></td>
<td><code>int</code></td>
<td>First occurrence, or -1</td>
</tr>
<tr>
<td><code>lastIndexOf(String str)</code></td>
<td><code>int</code></td>
<td>Last occurrence, or -1</td>
</tr>
<tr>
<td><code>contains(CharSequence s)</code></td>
<td><code>boolean</code></td>
<td>True if <code>s</code> appears anywhere</td>
</tr>
<tr>
<td><code>startsWith(String prefix)</code></td>
<td><code>boolean</code></td>
<td></td>
</tr>
<tr>
<td><code>endsWith(String suffix)</code></td>
<td><code>boolean</code></td>
<td></td>
</tr>
</tbody>
</table>
<p><strong>Transformation</strong> (all return a new <code>String</code>)</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>substring(int start)</code></td>
<td>From <code>start</code> to end</td>
</tr>
<tr>
<td><code>substring(int start, int end)</code></td>
<td>From <code>start</code> (inclusive) to <code>end</code> (exclusive)</td>
</tr>
<tr>
<td><code>toLowerCase(Locale locale)</code></td>
<td>Use <code>Locale.ROOT</code> for identifiers and tokens; avoid the no-argument form</td>
</tr>
<tr>
<td><code>toUpperCase(Locale locale)</code></td>
<td>Same; the no-argument form uses the default locale, which varies</td>
</tr>
<tr>
<td><code>strip()</code></td>
<td>Removes leading and trailing Unicode whitespace (Java 11)</td>
</tr>
<tr>
<td><code>stripLeading()</code>, <code>stripTrailing()</code></td>
<td>One side only (Java 11)</td>
</tr>
<tr>
<td><code>trim()</code></td>
<td>Removes characters with code point ≤ 32; predates <code>strip()</code></td>
</tr>
<tr>
<td><code>replace(CharSequence old, CharSequence new)</code></td>
<td>All literal occurrences</td>
</tr>
<tr>
<td><code>replaceAll(String regex, String replacement)</code></td>
<td>All regex matches</td>
</tr>
<tr>
<td><code>replaceFirst(String regex, String replacement)</code></td>
<td>First match only</td>
</tr>
<tr>
<td><code>repeat(int count)</code></td>
<td>Concatenate <em>n</em> copies (Java 11)</td>
</tr>
<tr>
<td><code>indent(int n)</code></td>
<td>Prepend <em>n</em> spaces to each line, adds trailing newline if absent (Java 12)</td>
</tr>
<tr>
<td><code>stripIndent()</code></td>
<td>Strips common leading whitespace, as a text block does (Java 15)</td>
</tr>
<tr>
<td><code>translateEscapes()</code></td>
<td>Interprets <code>\n</code>, <code>\t</code>, etc., in a string at runtime (Java 15)</td>
</tr>
</tbody>
</table>
<p><strong>Splitting and converting</strong></p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>split(String regex)</code></td>
<td>Returns <code>String[]</code></td>
</tr>
<tr>
<td><code>split(String regex, int limit)</code></td>
<td>Positive limit: at most that many parts; negative: no limit; zero: trailing empty strings removed</td>
</tr>
<tr>
<td><code>toCharArray()</code></td>
<td>Defensive copy as <code>char[]</code></td>
</tr>
<tr>
<td><code>getBytes(Charset charset)</code></td>
<td>Encode to bytes; always specify the charset</td>
</tr>
<tr>
<td><code>chars()</code></td>
<td><code>IntStream</code> of char values (Java 8)</td>
</tr>
</tbody>
</table>
<p><strong>Comparison</strong> (use <code>equals()</code> for content, never <code>==</code>)</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>equals(Object other)</code></td>
<td>Case-sensitive character comparison</td>
</tr>
<tr>
<td><code>equalsIgnoreCase(String other)</code></td>
<td>Case-insensitive</td>
</tr>
<tr>
<td><code>compareTo(String other)</code></td>
<td>Lexicographic; negative, zero, or positive</td>
</tr>
<tr>
<td><code>compareToIgnoreCase(String other)</code></td>
<td></td>
</tr>
</tbody>
</table>
<h2>Choosing the right tool</h2>
<p>Different scenarios, different tools.</p>
<p>If you are joining two or three values in a single expression, <code>+</code> is fine. The compiler translates it to a single-call operation.</p>
<p>If you are accumulating strings across loop iterations or conditionally appending to a buffer, use <code>StringBuilder</code>. Create it once before the loop, append inside, call <code>toString()</code> once at the end.</p>
<p>If you need a delimiter-separated string from a collection, <code>String.join()</code> or <code>Collectors.joining()</code> is cleaner than a manual <code>StringBuilder</code> with delimiter logic.</p>
<p>If you need alignment, padding, or format specifiers, use <code>formatted()</code> or <code>String.format()</code>. For locale-sensitive number formatting, such as a thousand separator or a currency symbol, use <code>String.format(Locale, format, args)</code>.</p>
<p>If you need to decode bytes from an external source into a string, use <code>new String(bytes, charset)</code> with an explicit <code>Charset</code>.</p>
<p>If multiple threads must share one mutable builder, use <code>StringBuffer</code>. Reconsider whether the design requires shared mutable state at all before reaching for it.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">StringJoiner sj = new StringJoiner(", ", "(", ")");
sj.setEmptyValue("empty");

System.out.println(sj);

sj.add("x");
System.out.println(sj);

StringJoiner other = new StringJoiner("-", "{", "}");
other.add("y").add("z");
sj.merge(other);
System.out.println(sj);
</code></pre>
<p>Predict each line of output. Then: if <code>other</code> had no elements added to it before the merge, what would the third <code>println</code> show?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Strings: what Java actually stores</title>
      <link>https://unkletayo.dev/engineering/core-java/06-strings-what-java-actually-stores/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/06-strings-what-java-actually-stores/</guid>
      <description>What a String stores internally, why immutability enables the string pool, every construction method with guidance on when each is appropriate, and how text blocks work.</description>
      <pubDate>Tue, 07 Jul 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>strings</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/06-strings-what-java-actually-stores.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/06-strings-what-java-actually-stores.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/06-strings-what-java-actually-stores.png" alt="Strings: what Java actually stores" /></p>
<pre><code class="language-java">String a = "hello";
String b = "hello";
System.out.println(a == b);  // true
</code></pre>
<p>In <a href="https://unkletayo.dev/engineering/core-java/05-objects-equality-and-identity/">Objects, equality and identity</a>, we established that <code>==</code> compares addresses. These two variables were not assigned from each other, yet they point to the same object. The explanation involves what a <code>String</code> stores internally and a structure the JVM maintains for string literals.</p>
<h2>What a String stores</h2>
<p>A <code>String</code> object holds its character data in a <code>private final byte[] value</code> field plus a single <code>private final byte coder</code> field. The coder is either 0 (Latin-1) or 1 (UTF-16).</p>
<p>This is a HotSpot implementation detail introduced in Java 9 as compact strings (JEP 254). Before Java 9, <code>String</code> stored characters in a <code>char[]</code>, always in UTF-16, always two bytes per character. The new layout stores characters in the Unicode range U+0000 to U+00FF (ASCII and most Western European characters) at one byte each. Only when a string contains characters outside that range does the storage switch to UTF-16, using two bytes per character throughout.</p>
<p>What this means in practice: <code>"hello"</code> takes 5 bytes of character data. <code>"hēllo"</code> takes 10 bytes because <code>ē</code> (U+0113) is outside the Latin-1 range. The character <code>é</code> (U+00E9) is within that range and still stores at one byte. For server-side code that mainly handles ASCII text (identifiers, URLs, JSON keys), compact strings roughly halve the memory that the JVM would have used before Java 9.</p>
<p>The Java Language Specification says nothing about byte arrays. From the language's perspective, <code>String</code> is a sequence of <code>char</code> values. The internal storage is an OpenJDK detail, invisible through any public API. What the JLS does guarantee: <code>String</code> is <code>final</code>. You cannot subclass it. That prevents a subclass from modifying the character data while the superclass believes it is immutable.</p>
<h2>Why String is immutable</h2>
<p>Once a <code>String</code> object is created, neither the array reference nor the array contents change. No <code>String</code> method modifies the byte array. <code>toLowerCase()</code>, <code>replace()</code>, and <code>substring()</code> all return a new <code>String</code> object. The original is unchanged.</p>
<p>Three things depend on this guarantee.</p>
<p><strong>Thread safety.</strong> Because a <code>String</code>'s contents never change after construction, any number of threads can read the same object without synchronization. This matters for strings used as map keys, class names, file paths, and configuration values, all of which routinely cross thread boundaries.</p>
<p><strong>Hash caching.</strong> <code>String</code> has a <code>private int hash</code> field, initially 0. The first call to <code>hashCode()</code> computes the hash from the byte array and stores the result. Every subsequent call returns the cached value. If strings were mutable, the cache would go stale. Because they are not, the cache is always valid, so using strings as <code>HashMap</code> keys is fast.</p>
<p><strong>The string pool.</strong> If two objects share the same character sequence and neither can change, they can safely share the same Java object. No caller can tell the difference. That is what the string pool exploits.</p>
<h2>The string pool</h2>
<p>The JVM maintains a table called the string pool, backed by a hash table of interned string objects. It lives on the heap. Its default size is 65536 buckets and can be tuned with <code>-XX:StringTableSize</code>.</p>
<p>When the JVM loads a class, it encounters string literals in the class's constant pool. For each literal, it looks up the string pool: if the pool holds an entry for that character sequence, the JVM uses the existing object; if not, it adds the new object and returns it. This is why <code>a == b</code> is <code>true</code> above. The class contains two references to the literal <code>"hello"</code>, and the JVM resolves both to the same pooled object.</p>
<p>Compile-time constant expressions also land in the pool. The Java compiler evaluates constant folding expressions, concatenations of literals or chains of <code>final</code> string variables, before producing bytecode. The result is treated as a literal.</p>
<pre><code class="language-java">final String prefix = "hel";
String s = prefix + "lo";  // compile-time constant, interned
</code></pre>
<p>But if either variable is not <code>final</code>, concatenation happens at runtime, and the result is not automatically pooled:</p>
<pre><code class="language-java">String prefix = "hel";      // not final
String s = prefix + "lo";   // runtime result, not in the pool
</code></pre>
<p>You can explicitly intern a string with <code>intern()</code>. If the pool holds an equal string, <code>intern()</code> returns that pooled object. If not, it adds the calling string to the pool and returns it.</p>
<pre><code class="language-java">String a = new String("hello");  // not pooled
String b = "hello";              // pooled literal

System.out.println(a == b);           // false
System.out.println(a.intern() == b);  // true
</code></pre>
<p>In modern Java, calling <code>intern()</code> manually is unusual. The G1 garbage collector can deduplicate string objects automatically at GC time with <code>-XX:+UseStringDeduplication</code>. That approach works without touching each string in code, but it deduplicates objects. It does not change their identity, so <code>==</code> comparisons still differ. The correct way to compare string content in application code is always <code>equals()</code>.</p>
<h2>Construction methods</h2>
<p>Java provides more ways to construct a <code>String</code> than most languages. Each fits a specific scenario.</p>
<p><strong>String literal: <code>"hello"</code></strong></p>
<p>The most common form. The compiler records the literal in the constant pool; the JVM interns it at class-load time. Use it for any fixed value in source code.</p>
<p><strong><code>new String(String original)</code></strong></p>
<p>Creates a new, distinct object from an existing string. The new object is not pooled.</p>
<pre><code class="language-java">String s = new String("hello");  // new object, not in the pool
</code></pre>
<p>This is almost always a mistake. The only historical use, preventing a large backing array from being retained through a <code>substring()</code> reference, no longer applies. Modern JDK <code>substring()</code> does not share storage with the original. Avoid this constructor.</p>
<p><strong><code>new String(byte[] bytes, Charset charset)</code></strong></p>
<p>The correct way to decode bytes from an external source, such as a file, a network socket, or a database driver, into a Java string.</p>
<pre><code class="language-java">byte[] received = inputStream.readNBytes(length);
String message = new String(received, StandardCharsets.UTF_8);
</code></pre>
<p>Always specify the charset explicitly. The overload <code>new String(byte[])</code> uses the platform default charset, which varies by JVM configuration and operating system. Code that depends on the default charset can silently produce different results on different machines.</p>
<p><strong><code>new String(char[] value)</code></strong></p>
<p>Creates a string from a char array with a defensive copy. Changes to the array after construction do not affect the string. Use this when you have already built up a <code>char[]</code> and need a <code>String</code>.</p>
<p><strong><code>String.valueOf(Object obj)</code></strong></p>
<p>Returns <code>"null"</code> if <code>obj</code> is null, otherwise calls <code>obj.toString()</code>. Use this when you need a string representation of an object that might be null.</p>
<pre><code class="language-java">String s = String.valueOf(account);  // "null" if account is null
</code></pre>
<p>The primitive overloads, <code>String.valueOf(int)</code>, <code>String.valueOf(long)</code>, and <code>String.valueOf(boolean)</code>, convert primitives without boxing. They are equivalent to <code>Integer.toString(n)</code>, <code>Long.toString(n)</code>, and <code>Boolean.toString(b)</code>.</p>
<p><strong><code>String.format()</code> and <code>str.formatted()</code></strong></p>
<p>Both produce a formatted string using <code>printf</code>-style specifiers: <code>%s</code> for strings, <code>%d</code> for integers, <code>%f</code> for floats, <code>%n</code> for the platform line separator.</p>
<pre><code class="language-java">String msg = String.format("Account %s, balance %d", id, balance);
String msg2 = "Account %s, balance %d".formatted(id, balance);
</code></pre>
<p><code>formatted()</code> is an instance method added in Java 15. It calls <code>String.format()</code> internally. Use <code>formatted()</code> when the format string is a literal in source code. Use <code>String.format(Locale, format, args)</code> when you need locale-specific number formatting, such as <code>%,d</code> for a thousand-separated integer.</p>
<p>Both involve <code>Formatter</code> parsing overhead on every call. For simple concatenation without alignment or padding, <code>+</code> or <code>StringBuilder</code> is more direct. The next article covers when each is appropriate.</p>
<p><strong><code>String.join()</code></strong></p>
<p>Joins strings with a separator without writing a loop.</p>
<pre><code class="language-java">String csv = String.join(", ", "Alice", "Bob", "Carol");
// "Alice, Bob, Carol"

List&lt;String&gt; ids = List.of("A001", "A002", "A003");
String joined = String.join(", ", ids);
</code></pre>
<p>Internally, <code>String.join()</code> delegates to <code>StringJoiner</code>. The next article covers <code>StringJoiner</code> directly.</p>
<h2>Text blocks</h2>
<p>A text block is a multiline string literal introduced in Java 15 (JEP 378). The opening delimiter is <code>"""</code> followed immediately by a newline. The closing delimiter is <code>"""</code> on its own line.</p>
<pre><code class="language-java">String json = """
        {
            "id": "A001",
            "balance": 5000
        }
        """;
</code></pre>
<p>The JVM strips leading whitespace from each content line. The minimum indentation of all non-empty content lines determines how much. In this example, both the content and the closing <code>"""</code> are indented 8 spaces, so 8 spaces are stripped from every line. Move the closing <code>"""</code> to column 0 to strip no whitespace.</p>
<p>Three escape sequences are specific to text blocks.</p>
<p>A <code>\</code> at the end of a line suppresses the newline:</p>
<pre><code class="language-java">String s = """
        Hello \
        World""";
// equivalent to "Hello World"
</code></pre>
<p><code>\s</code> inserts a space and prevents the compiler from stripping trailing whitespace from that position:</p>
<pre><code class="language-java">String row = """
        Alice   \s
        Bob     \s
        """;
</code></pre>
<p>A text block is a regular <code>String</code> at runtime. It participates in the string pool just like any other literal, and format specifiers work the same way:</p>
<pre><code class="language-java">String query = """
        SELECT *
        FROM accounts
        WHERE id = '%s'
        """.formatted(accountId);
</code></pre>
<p>Text blocks were available as a preview feature in Java 13 and 14; the preview form differs from the final version. Use only the Java 15 form in production code.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">String a = "java";
String b = "ja" + "va";
String part = "va";
String c = "ja" + part;
String d = new String("java").intern();

System.out.println(a == b);
System.out.println(a == c);
System.out.println(a == d);
</code></pre>
<p>Predict each output. Then: how would your answers change if <code>part</code> were declared <code>final</code>?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Objects, equality and identity</title>
      <link>https://unkletayo.dev/engineering/core-java/05-objects-equality-and-identity/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/05-objects-equality-and-identity/</guid>
      <description>What happens when you call new, the difference between object identity and equality, how equals() and hashCode() work together, the string pool, and why overriding one without the other breaks collections.</description>
      <pubDate>Tue, 30 Jun 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>oop</category>
      <category>equals</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/05-objects-equality-and-identity.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/05-objects-equality-and-identity.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/05-objects-equality-and-identity.png" alt="Objects, equality and identity" /></p>
<pre><code class="language-java">Account a1 = new Account("Adetayo", 5000);
Account a2 = new Account("Adetayo", 5000);
System.out.println(a1 == a2);
</code></pre>
<p>This prints <code>false</code>. Same class, same field values, different result. If you expected <code>true</code>, or you're not sure why it's false, this article is the explanation.</p>
<h2>What new does</h2>
<p>The <code>new</code> keyword creates an object in three steps.</p>
<p>First, the JVM allocates memory on the heap for the new object. The amount of memory depends on the class's fields. An <code>Account</code> with two fields (a <code>String</code> reference and an <code>int</code>) needs space for those two slots plus an object header. The header stores bookkeeping information the JVM needs: the type of the object (a pointer to its class metadata), and flags used by the garbage collector and synchronisation mechanism.</p>
<p>Second, the JVM runs the constructor. The constructor's job is to put the new object into a valid initial state. It can set fields, call other methods, or call a parent class constructor with <code>super(...)</code>. The constructor receives <code>this</code>, a reference to the newly allocated object, as its implicit first argument.</p>
<p>Third, the <code>new</code> expression evaluates to the address of the new object. That address is what gets stored in your reference variable.</p>
<pre><code class="language-java">Account a1 = new Account("Adetayo", 5000);
</code></pre>
<p>The <code>Account</code> object is on the heap. <code>a1</code> holds its address. Every call to <code>new Account(...)</code> allocates a new, distinct object at a new address, even if the constructor arguments are identical.</p>
<h2>Identity: the address is the identity</h2>
<p>An object's identity is its location in memory. Two objects are the same object if and only if they occupy the same memory location, meaning they have the same address.</p>
<p>The <code>==</code> operator on reference variables checks addresses. <code>a1 == a2</code> asks: does <code>a1</code> hold the same address as <code>a2</code>? Since <code>new Account(...)</code> was called twice, two separate objects were allocated at two different addresses. <code>a1 == a2</code> is <code>false</code>.</p>
<p>This is true even if every field has the same value:</p>
<pre><code class="language-java">Account a1 = new Account("Adetayo", 5000);
Account a2 = new Account("Adetayo", 5000);
// a1.name == a2.name might be true (string pool, discussed below)
// a1.balance == a2.balance is true (same int value)
// a1 == a2 is false (different heap addresses)
</code></pre>
<p>Identity is about which object, not what values it holds.</p>
<p>A reference variable assigned <code>null</code> holds no address at all. <code>null == null</code> is <code>true</code>; <code>a1 == null</code> is <code>false</code> for any non-null reference.</p>
<h2>Equality: comparing content</h2>
<p>Identity is not always what you want. If you have two separate <code>Account</code> objects representing the same account, perhaps one fetched from a database and one held in memory, you might consider them equal if their account IDs match, regardless of whether they're the same Java object.</p>
<p>This is what <code>equals()</code> is for.</p>
<p>Every class inherits <code>equals(Object other)</code> from <code>java.lang.Object</code>. The default implementation provided by <code>Object</code> checks identity: <code>return this == other</code>. It's the same as <code>==</code>.</p>
<p>To compare content, you override <code>equals()</code> in your class:</p>
<pre><code class="language-java">public class Account {
    private final String id;
    private int balance;

    public Account(String id, int balance) {
        this.id = id;
        this.balance = balance;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (!(other instanceof Account)) return false;
        Account that = (Account) other;
        return this.id.equals(that.id);
    }
}
</code></pre>
<p>Now <code>a1.equals(a2)</code> checks IDs rather than addresses. Two <code>Account</code> objects with the same ID are equal according to this method, even though <code>a1 == a2</code> is still <code>false</code>.</p>
<h2>The hashCode contract</h2>
<p>Whenever you override <code>equals()</code>, you must also override <code>hashCode()</code>. This is not a style suggestion. It's a contract. The JLS (§11.2 of the Object specification, via java.lang.Object API documentation) states:</p>
<blockquote>
<p>If two objects are equal according to the <code>equals(Object)</code> method, then calling the <code>hashCode</code> method on each of the two objects must produce the same integer result.</p>
</blockquote>
<p><code>HashMap</code> and <code>HashSet</code> depend on this contract. When you call <code>map.get(key)</code>, the map first calls <code>key.hashCode()</code> to find the right bucket in its internal array, then uses <code>equals()</code> to find the matching entry within that bucket. If two equal objects have different hash codes, <code>get</code> will look in the wrong bucket and not find the entry, even though it's there.</p>
<p>Here's the failure mode:</p>
<pre><code class="language-java">public class BrokenAccount {
    private final String id;
    // ... constructor ...

    @Override
    public boolean equals(Object other) {
        if (!(other instanceof BrokenAccount)) return false;
        return this.id.equals(((BrokenAccount) other).id);
    }
    // hashCode NOT overridden — inherits Object's default, which uses identity
}

Map&lt;BrokenAccount, Integer&gt; ledger = new HashMap&lt;&gt;();
BrokenAccount acc = new BrokenAccount("A001");
ledger.put(acc, 5000);

BrokenAccount lookup = new BrokenAccount("A001");
System.out.println(ledger.get(lookup));  // null — not found!
</code></pre>
<p><code>acc.equals(lookup)</code> returns <code>true</code> (same ID). But <code>acc.hashCode()</code> and <code>lookup.hashCode()</code> return different values (identity-based defaults from two different objects). The map stores the entry in the bucket for <code>acc.hashCode()</code>, then looks for it in the bucket for <code>lookup.hashCode()</code>. Different buckets. Entry not found.</p>
<p>The fix: override <code>hashCode()</code> based on the same fields that <code>equals()</code> uses.</p>
<pre><code class="language-java">@Override
public int hashCode() {
    return id.hashCode();
}
</code></pre>
<p>Now equal accounts produce equal hash codes, and <code>HashMap</code> works correctly.</p>
<p>Modern Java makes this easier. Records automatically generate correct <code>equals()</code> and <code>hashCode()</code> implementations based on all their components. And IDE tools can generate them for regular classes. But you should understand why the contract exists before relying on generated code to satisfy it.</p>
<h2>State, behavior, identity</h2>
<p>It's worth naming these three dimensions explicitly, because they describe what an object is.</p>
<p><strong>State</strong> is the current values of the object's fields. An <code>Account</code> with balance 5000 has different state from one with balance 3000, even if they're otherwise identical.</p>
<p><strong>Behavior</strong> is what the object's methods do. <code>deposit(100)</code> and <code>withdraw(50)</code> are behaviors. Two objects of the same class have the same behaviors.</p>
<p><strong>Identity</strong> is what distinguishes this object from all others. In Java, identity is the object's address. It doesn't change over the object's lifetime (from Java code's perspective, the GC may move objects internally, but it updates all references to maintain consistency).</p>
<p>Two objects can share state and class (identical fields, same type) and still be distinct objects with separate identities. This is exactly <code>a1</code> and <code>a2</code> above.</p>
<h2>The string pool</h2>
<p>String literals are a special case worth knowing.</p>
<p>When the compiler sees <code>"hello"</code> as a literal in source code, it records the string in the class's constant pool. At runtime, the JVM maintains a <strong>string pool</strong>, a table of interned strings. The first time <code>"hello"</code> is needed, an object is created and added to the pool. The next time <code>"hello"</code> is needed from any class, the same object is returned.</p>
<p>This means string literals with the same content often share the same object:</p>
<pre><code class="language-java">String a = "hello";
String b = "hello";
System.out.println(a == b);   // true — same pooled object
</code></pre>
<p>But <code>new String("hello")</code> bypasses the pool and always allocates a new object:</p>
<pre><code class="language-java">String c = new String("hello");
String d = new String("hello");
System.out.println(c == d);   // false — two distinct objects
System.out.println(c.equals(d));  // true — same character sequence
</code></pre>
<p>This is why you should compare strings with <code>equals()</code>, not <code>==</code>. Code that works in a test might break in production if the string was constructed differently and isn't pooled. <code>equals()</code> on <code>String</code> compares the characters; <code>==</code> compares addresses.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">public class Point {
    int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }
}

Point p1 = new Point(3, 4);
Point p2 = new Point(3, 4);
Point p3 = p1;

System.out.println(p1 == p2);
System.out.println(p1 == p3);
System.out.println(p1.equals(p2));
System.out.println(p1.equals(p3));
</code></pre>
<p>Predict each output before running. Then: if you override <code>equals()</code> in <code>Point</code> to compare <code>x</code> and <code>y</code> fields, what do <code>p1.equals(p2)</code> and <code>p1.equals(p3)</code> return? And if you override <code>equals()</code> but forget <code>hashCode()</code>, what breaks?</p>
]]></content:encoded>
    </item>
    <item>
      <title>Methods and the call stack</title>
      <link>https://unkletayo.dev/engineering/core-java/04-methods-and-the-call-stack/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/04-methods-and-the-call-stack/</guid>
      <description>How Java methods work at the JVM level: stack frames, local variable slots, the operand stack, pass-by-value for primitives and references, and why swap(a, b) never works.</description>
      <pubDate>Tue, 23 Jun 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>jvm</category>
      <category>methods</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/04-methods-and-the-call-stack.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/04-methods-and-the-call-stack.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/04-methods-and-the-call-stack.png" alt="Methods and the call stack" /></p>
<p>Imagine you're building an application that sends notifications. At three different points in your code, you need to format a message, add a timestamp, and pass it to a delivery service. Without methods, you copy those fifteen lines of logic three times. When a bug surfaces in the formatting, you fix it in one place and forget the other two.</p>
<p>Methods solve this, not just as a convenience, but as a fundamental mechanism for organising computation. A method is a named, reusable sequence of instructions. Call it from anywhere, pass in what it needs, get back what it computed. The JVM has a specific structure for making this work at runtime: the call stack.</p>
<h2>The call stack and stack frames</h2>
<p>Each thread in a JVM process has its own call stack. The stack is a last-in, first-out sequence of frames. When a method is called, a new frame is pushed onto the stack. When the method returns, its frame is popped off and discarded.</p>
<p>A frame holds everything the currently executing method needs:</p>
<ul>
<li><strong>Local variable slots</strong>: numbered storage locations. Slot 0 in an instance method holds <code>this</code>; in a <code>static</code> method, slot 0 is the first parameter. Each parameter and each local variable declared inside the method occupies one or two slots (two for <code>long</code> and <code>double</code>, which are 64 bits wide).</li>
<li><strong>Operand stack</strong>: a small working area used by bytecode instructions. When you write <code>a + b</code>, the JVM loads the values of <code>a</code> and <code>b</code> onto the operand stack, then executes an <code>iadd</code> instruction that pops both, adds them, and pushes the result.</li>
<li><strong>A reference to the constant pool</strong> of the current class, used to resolve symbolic names to runtime objects.</li>
</ul>
<p>Consider this program:</p>
<pre><code class="language-java">public class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        int result = add(3, 4);
        System.out.println(result);
    }
}
</code></pre>
<p>Trace what happens when <code>main</code> calls <code>add(3, 4)</code>:</p>
<ol>
<li><code>main</code>'s frame is on the stack. The JVM evaluates the arguments, the int literals <code>3</code> and <code>4</code>.</li>
<li>The JVM pushes a new frame for <code>add</code>. Slot 0 of the <code>add</code> frame gets the value <code>3</code>; slot 1 gets the value <code>4</code>. These are copies of the argument values.</li>
<li>Inside <code>add</code>, the bytecode instructions load slot 0 and slot 1 onto the operand stack (<code>iload_0</code>, <code>iload_1</code>), execute <code>iadd</code> to produce 7, and return with <code>ireturn</code>.</li>
<li>The <code>add</code> frame is popped. The return value 7 is placed on <code>main</code>'s operand stack. <code>main</code> stores it in its local variable slot for <code>result</code>.</li>
<li><code>main</code> calls <code>System.out.println(result)</code>, which triggers another frame push, executes, and returns.</li>
</ol>
<p>Each method's frame is completely private to that invocation. The <code>add</code> method cannot see <code>main</code>'s variables. <code>main</code> cannot see <code>add</code>'s variables. When a frame is popped, its slots are gone.</p>
<h2>Parameters are copies</h2>
<p>When the JVM pushes a new frame, it copies the argument values into the new frame's local variable slots. This is the whole meaning of "Java is pass-by-value". The parameter slot always contains a copy of what was passed.</p>
<p>For a primitive, the copy is the number.</p>
<pre><code class="language-java">public static void doubleIt(int n) {
    n = n * 2;
    System.out.println("inside: " + n);  // 10
}

public static void main(String[] args) {
    int x = 5;
    doubleIt(x);
    System.out.println("after: " + x);   // 5
}
</code></pre>
<p>The <code>doubleIt</code> frame gets a copy of <code>5</code> in slot 0. Multiplying and assigning changes only that slot. The <code>x</code> slot in <code>main</code>'s frame is untouched.</p>
<p>This means a traditional <code>swap</code> function cannot work in Java:</p>
<pre><code class="language-java">public static void swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}

// In main:
int x = 1, y = 2;
swap(x, y);
// x is still 1, y is still 2
</code></pre>
<p><code>swap</code> exchanges the values in its own slots. Those slots contain copies. The originals in <code>main</code>'s frame are never touched.</p>
<h2>Parameters are copies, including reference parameters</h2>
<p>For a reference variable, the copy is the address. The parameter slot gets a copy of the address the caller passed.</p>
<p>This creates the apparent contradiction that confuses newcomers: you can call a method and have it modify an object, but you can't have it reassign the caller's variable.</p>
<p>Here's the modification case:</p>
<pre><code class="language-java">public static void appendGreeting(StringBuilder sb) {
    sb.append(" — have a good day");
}

public static void main(String[] args) {
    StringBuilder message = new StringBuilder("Hello");
    appendGreeting(message);
    System.out.println(message);  // Hello — have a good day
}
</code></pre>
<p><code>appendGreeting</code> gets a copy of the address stored in <code>message</code>. Both <code>message</code> (in <code>main</code>'s frame) and <code>sb</code> (in <code>appendGreeting</code>'s frame) hold the same address. They refer to the same <code>StringBuilder</code> object in the heap. Calling <code>sb.append(...)</code> modifies the object at that address. When <code>appendGreeting</code> returns, <code>message</code> in <code>main</code>'s frame still holds the same address, and the object at that address now has the modified content.</p>
<p>Here's the reassignment case:</p>
<pre><code class="language-java">public static void replaceMessage(StringBuilder sb) {
    sb = new StringBuilder("Goodbye");
}

public static void main(String[] args) {
    StringBuilder message = new StringBuilder("Hello");
    replaceMessage(message);
    System.out.println(message);  // Hello
}
</code></pre>
<p>Inside <code>replaceMessage</code>, <code>sb = new StringBuilder(...)</code> stores a new address in the <code>sb</code> slot of the <code>replaceMessage</code> frame. That slot is local to this frame. It has no connection to <code>message</code>'s slot in <code>main</code>'s frame. When <code>replaceMessage</code> returns, its frame is gone, and <code>message</code> in <code>main</code> still holds the original address. <code>"Hello"</code> is unaffected.</p>
<p>The rule is consistent. Java copies the value. For a reference, the value is an address. The method can use that address to reach and modify the object, but it cannot change which object the caller's variable points to, because the method only has a copy of the address.</p>
<h2>Stack frames in the bytecode</h2>
<p>If you compile the <code>Calculator</code> example and run <code>javap -c Calculator.class</code>, you'll see the actual instructions. The local variable slots appear as numbered indices in instructions like <code>iload_0</code> (load int from slot 0), <code>istore_1</code> (store int to slot 1), <code>aload_0</code> (load reference from slot 0). The <code>a</code> for slot 0 tells you that some instructions are reference-typed; <code>i</code> slots hold integers; <code>l</code>, <code>f</code>, <code>d</code> hold longs, floats, and doubles.</p>
<p>HotSpot's JIT compiler may eliminate individual frames through inlining. A small method can have its instructions merged directly into the caller, removing the frame push and pop entirely. From the JLS perspective this is invisible: inlining is a performance optimisation that doesn't change what the program does. The mental model of frames is still the right model for reasoning about scope, parameter passing, and variable lifetime.</p>
<h2>Stack depth and StackOverflowError</h2>
<p>The call stack has a fixed maximum depth (configurable with <code>-Xss</code>). Every method call pushes a frame; methods that never return keep the stack growing. Eventually the JVM runs out of stack space and throws a <code>StackOverflowError</code>.</p>
<p>The most common cause is unbounded recursion:</p>
<pre><code class="language-java">public static void infinite() {
    infinite();  // pushes a frame, which calls infinite, which pushes a frame...
}
</code></pre>
<p>Each call to <code>infinite</code> pushes a frame before the previous one has returned. After some thousands of frames (depending on JVM settings and frame size), the stack is full.</p>
<p>Recursion is not inherently a problem. A correctly written recursive method has a base case that returns without recursing, limiting the depth. A depth of a few hundred is usually fine. Depths of tens of thousands may need a different approach, or explicit stack management. That's a topic for later in this series.</p>
<h2>Prediction exercise</h2>
<p>What does this print?</p>
<pre><code class="language-java">public static void modify(int[] arr) {
    arr[0] = 99;
    arr = new int[]{0, 0, 0};
}

public static void main(String[] args) {
    int[] data = {1, 2, 3};
    modify(data);
    System.out.println(data[0]);
    System.out.println(data.length);
}
</code></pre>
<p>Trace it: <code>modify</code> receives a copy of the address stored in <code>data</code>. <code>arr[0] = 99</code> uses that address to modify the original array, so <code>data[0]</code> is affected. Then <code>arr = new int[]{0, 0, 0}</code> replaces the address in <code>modify</code>'s local slot, so <code>data</code> in <code>main</code> is not affected. After <code>modify</code> returns, <code>data</code> still points to the original array, now <code>{99, 2, 3}</code>.</p>
<p>Work through the full trace, then run it to verify. If you got it right, you understand pass-by-value for reference types.</p>
]]></content:encoded>
    </item>
    <item>
      <title>Assignment and what gets copied</title>
      <link>https://unkletayo.dev/engineering/core-java/03-assignment-and-what-gets-copied/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/03-assignment-and-what-gets-copied/</guid>
      <description>What Java&apos;s assignment operator actually does: copying primitive values vs copying addresses, aliasing, mutation through shared references, and what null means.</description>
      <pubDate>Tue, 16 Jun 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>references</category>
      <category>memory</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/03-assignment-and-what-gets-copied.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/03-assignment-and-what-gets-copied.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/03-assignment-and-what-gets-copied.png" alt="Assignment and what gets copied" /></p>
<pre><code class="language-java">int[] arr1 = {1, 2, 3};
int[] arr2 = arr1;
arr2[0] = 99;
System.out.println(arr1[0]);
</code></pre>
<p>What does this print?</p>
<p>A lot of Java confusion traces back to this question. The answer is <code>99</code>. We only wrote to <code>arr2</code>, but <code>arr1[0]</code> changed. This isn't a bug in Java. It's the direct consequence of what <code>=</code> does to a reference variable, and once you understand that, the behaviour is obvious.</p>
<h2>Assignment copies the value</h2>
<p>The <code>=</code> operator always copies the value on the right into the storage location on the left. For primitives, the value is the number itself.</p>
<pre><code class="language-java">int a = 5;
int b = a;
a = 10;
System.out.println(b);  // 5
</code></pre>
<p><code>b</code> gets a copy of the bits in <code>a</code> at the moment of assignment: the value <code>5</code>. Changing <code>a</code> afterward has no effect on <code>b</code>. They're independent.</p>
<p>For a reference variable, the value is not the object. It's the address of the object. That address is what gets copied.</p>
<pre><code class="language-java">String x = "hello";
String y = x;
</code></pre>
<p>After this, <code>x</code> and <code>y</code> both hold the same address. They point to the same <code>String</code> object in the heap. This is called <strong>aliasing</strong>: two names for the same thing.</p>
<p>Now:</p>
<pre><code class="language-java">y = "world";
</code></pre>
<p>This replaces the address stored in <code>y</code> with the address of a different <code>String</code> object. It does not touch the <code>"hello"</code> object. <code>x</code> still holds the original address, so <code>x</code> still points to <code>"hello"</code>. Reassigning <code>y</code> only changes what <code>y</code> holds; it cannot change what <code>x</code> holds.</p>
<h2>Modifying through a shared reference</h2>
<p>Reassigning is different from mutating. When you have two references to the same object, and you use one of them to modify the object's state, both references see the change, because there's only one object.</p>
<pre><code class="language-java">StringBuilder sb = new StringBuilder("hello");
StringBuilder copy = sb;
copy.append(" world");
System.out.println(sb);    // hello world
System.out.println(copy);  // hello world
</code></pre>
<p><code>sb</code> and <code>copy</code> hold the same address. They both refer to the same <code>StringBuilder</code> object. Calling <code>copy.append(...)</code> modifies that object in place. Because <code>sb</code> points to the same object, <code>sb</code> sees the modification. This isn't surprising once you know that <code>copy = sb</code> copied the address, not the object.</p>
<p>Now go back to the array example:</p>
<pre><code class="language-java">int[] arr1 = {1, 2, 3};
int[] arr2 = arr1;
arr2[0] = 99;
System.out.println(arr1[0]);  // 99
</code></pre>
<p><code>arr2 = arr1</code> copies the address. Both variables point to the same array in the heap. <code>arr2[0] = 99</code> writes to slot 0 of that array. Since <code>arr1</code> points to the same array, <code>arr1[0]</code> reflects the change.</p>
<p>Contrast this with:</p>
<pre><code class="language-java">arr2 = new int[]{7, 8, 9};
</code></pre>
<p>This creates a new array and stores its address in <code>arr2</code>. Now <code>arr2</code> points to a different array. <code>arr1</code> is unchanged, still pointing to <code>{1, 2, 3}</code> (or <code>{99, 2, 3}</code> if the previous mutation already happened). Reassigning <code>arr2</code> changes only what <code>arr2</code> holds.</p>
<p>The rule is consistent: <code>=</code> copies the value. For a reference, the value is an address, not an object. Aliasing is assignment doing exactly what it says.</p>
<h2>null: a reference that points nowhere</h2>
<p>A reference variable doesn't have to hold the address of an object. It can hold <code>null</code>, a special value meaning "no object here."</p>
<pre><code class="language-java">String s = null;
System.out.println(s);        // null (println handles null specially)
System.out.println(s.length()); // NullPointerException
</code></pre>
<p><code>s</code> holds null, not an address. When you call <code>s.length()</code>, the JVM tries to dispatch the method call to the object at the address in <code>s</code>. There's no address. There's no object. The JVM throws a <code>NullPointerException</code>.</p>
<p><code>null</code> is not an empty string, not a zero-length array, not a default object. It's the absence of a reference. A <code>String</code> variable is null by default if declared as a field without initialisation; a local variable is not given a default and must be initialised before use. The compiler enforces this.</p>
<pre><code class="language-java">String a = "";      // a reference to an empty String object
String b = null;    // no object at all
int len = a.length();  // 0 — fine
int len2 = b.length(); // NullPointerException
</code></pre>
<p>The distinction matters often enough that Java 14 added helpful NullPointerException messages that tell you which variable was null and which method was being called.</p>
<h2>What "immutable" means in this model</h2>
<p><code>String</code> is immutable. No method on <code>String</code> changes the string's characters. Every method that seems to modify a string (like <code>replace</code>, <code>toUpperCase</code>, <code>substring</code>) returns a new <code>String</code> object and leaves the original untouched.</p>
<pre><code class="language-java">String s = "hello";
String t = s.toUpperCase();
System.out.println(s);  // hello
System.out.println(t);  // HELLO
</code></pre>
<p><code>s</code> and <code>t</code> now hold different addresses. <code>s</code> still points to <code>"hello"</code>. <code>t</code> points to the new <code>"HELLO"</code> object. The original string was not modified. <code>String</code> objects have no method that could modify them.</p>
<p>This matters for aliasing. With a mutable object like <code>StringBuilder</code>, two references sharing the same object means mutations are visible from both. With an immutable object like <code>String</code>, this concern disappears. You can share a <code>String</code> reference freely because nothing can change the object it points to.</p>
<h2>The practical pattern to watch for</h2>
<p>The mistake that bites new Java developers most often is assuming that assigning a reference variable copies the object.</p>
<pre><code class="language-java">// Wrong mental model: does this protect arr1?
int[] arr1 = {1, 2, 3};
int[] backup = arr1;
// 'backup' doesn't protect arr1 from mutation through arr1
// it *is* arr1 — same array, two names
</code></pre>
<p>If you want an independent copy of an array, you need to copy the array itself:</p>
<pre><code class="language-java">int[] backup = Arrays.copyOf(arr1, arr1.length);
// or:
int[] backup = arr1.clone();
</code></pre>
<p>Now <code>backup</code> points to a new array with the same values. Mutations through <code>arr1</code> don't affect <code>backup</code>, and vice versa.</p>
<h2>Prediction exercise</h2>
<pre><code class="language-java">StringBuilder a = new StringBuilder("cat");
StringBuilder b = a;
StringBuilder c = new StringBuilder(a.toString());

b.append("s");
c.append("s");

System.out.println(a);
System.out.println(b);
System.out.println(c);
</code></pre>
<p>Predict what each line prints before you run it. Trace which variables share the same object in the heap, and which are independent. The answer follows directly from what you now know about assignment: <code>b = a</code> copied the address; <code>new StringBuilder(a.toString())</code> created a new object.</p>
]]></content:encoded>
    </item>
    <item>
      <title>How Java stores values</title>
      <link>https://unkletayo.dev/engineering/core-java/02-how-java-stores-values/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/02-how-java-stores-values/</guid>
      <description>How Java&apos;s type system maps to memory: two&apos;s complement integers, IEEE 754 floats, the eight primitive types, reference variables as addresses, and why the stack and heap are structured the way they are.</description>
      <pubDate>Tue, 09 Jun 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>jvm</category>
      <category>memory</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/02-how-java-stores-values.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/02-how-java-stores-values.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/02-how-java-stores-values.png" alt="How Java stores values" /></p>
<p>When you write <code>int x = 42</code>, your computer stores something in memory. Not the character <code>4</code> followed by <code>2</code>. Not some abstract notion of "forty-two". A specific pattern of bits that the CPU knows how to add, compare, and shift. When you write <code>String name = "Adetayo"</code>, something different happens. Understanding that difference is the foundation for reasoning about Java programs.</p>
<h2>Bits, bytes, and two's complement</h2>
<p>A bit is a single binary digit: 0 or 1. A byte is 8 bits. With 8 bits you can represent 2^8 = 256 distinct values. The question is which 256.</p>
<p>Java uses <strong>two's complement</strong> for all integer types. In two's complement, the most significant bit (the leftmost one) is the sign bit. When it's 0, the remaining 7 bits give values from 0 to 127. When it's 1, you're in negative territory. The range for <code>byte</code> is -128 to 127, not -127 to 127. Here's why: 256 combinations split as 128 non-negative (0 through 127) and 128 negative (-128 through -1). Zero takes one combination from the non-negative side.</p>
<table>
<thead>
<tr>
<th>Bits</th>
<th>Decimal</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>01111111</code></td>
<td>127</td>
</tr>
<tr>
<td><code>00000001</code></td>
<td>1</td>
</tr>
<tr>
<td><code>00000000</code></td>
<td>0</td>
</tr>
<tr>
<td><code>11111111</code></td>
<td>-1</td>
</tr>
<tr>
<td><code>10000000</code></td>
<td>-128</td>
</tr>
</tbody>
</table>
<p>The useful property of two's complement is that addition works identically regardless of sign. The CPU uses the same adder circuit for <code>3 + 4</code> and <code>3 + (-4)</code>. That's the practical reason it was chosen.</p>
<p>Integer arithmetic in Java wraps around at the boundary. <code>Integer.MAX_VALUE + 1</code> does not throw an exception. It produces <code>Integer.MIN_VALUE</code>. The 32-bit pattern for <code>Integer.MAX_VALUE</code> is <code>01111111 11111111 11111111 11111111</code>. Adding 1 flips it to <code>10000000 00000000 00000000 00000000</code>, which in two's complement is <code>-2147483648</code>. The JLS specifies this in section 15.18.2: integer addition is performed modulo 2^32 for <code>int</code>. Silently, defined, and your responsibility to guard against when it matters.</p>
<pre><code class="language-java">int max = Integer.MAX_VALUE;
System.out.println(max);       // 2147483647
System.out.println(max + 1);   // -2147483648
</code></pre>
<h2>The eight primitive types</h2>
<p>Java has exactly eight primitive types. Their sizes and ranges are fixed by the JLS. They don't vary between platforms, which was a deliberate design choice for portability.</p>
<table>
<thead>
<tr>
<th>Type</th>
<th>Size</th>
<th>Range / notes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>boolean</code></td>
<td>1 bit (conceptually; JVM may use 1 byte in arrays)</td>
<td><code>true</code> or <code>false</code></td>
</tr>
<tr>
<td><code>byte</code></td>
<td>8 bits</td>
<td>-128 to 127</td>
</tr>
<tr>
<td><code>short</code></td>
<td>16 bits</td>
<td>-32,768 to 32,767</td>
</tr>
<tr>
<td><code>char</code></td>
<td>16 bits</td>
<td>0 to 65,535; unsigned UTF-16 code unit</td>
</tr>
<tr>
<td><code>int</code></td>
<td>32 bits</td>
<td>-2,147,483,648 to 2,147,483,647</td>
</tr>
<tr>
<td><code>long</code></td>
<td>64 bits</td>
<td>-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807</td>
</tr>
<tr>
<td><code>float</code></td>
<td>32 bits</td>
<td>IEEE 754 single precision</td>
</tr>
<tr>
<td><code>double</code></td>
<td>64 bits</td>
<td>IEEE 754 double precision</td>
</tr>
</tbody>
</table>
<p><code>char</code> deserves a note. It's a 16-bit unsigned integer representing a single UTF-16 code unit. This covers code points U+0000 through U+FFFF, which includes most characters in common use. Code points beyond U+FFFF, including many emoji and rare scripts, require two <code>char</code> values, called a surrogate pair. So <code>char</code> is not a "character" in the Unicode sense; it's a 16-bit storage unit that sometimes needs a partner.</p>
<p><code>float</code> and <code>double</code> follow IEEE 754. A 64-bit <code>double</code> splits its bits as 1 sign, 11 exponent, 52 significand. Most decimal fractions cannot be represented exactly in binary. <code>0.1</code> in binary is a repeating fraction. When you write <code>double x = 0.1</code>, <code>x</code> holds the nearest representable value, which differs from 0.1 by about 5.5 × 10^-18. That's why:</p>
<pre><code class="language-java">System.out.println(0.1 + 0.2);         // 0.30000000000000004
System.out.println(0.1 + 0.2 == 0.3);  // false
</code></pre>
<p>This is not a Java bug. It's IEEE 754 arithmetic, used by every major language and processor. When exact decimal arithmetic matters, as in financial calculations, use <code>BigDecimal</code>.</p>
<h2>What a primitive variable is</h2>
<p>A primitive variable is a named storage location that holds the bits directly. When you write <code>int x = 42</code>, the variable <code>x</code> is a 32-bit slot containing the two's complement pattern for 42. When you write <code>int y = x</code>, the slot for <code>y</code> gets its own copy of those same 32 bits. <code>x</code> and <code>y</code> are independent. Changing one has no effect on the other.</p>
<p>This directness is why primitives exist as a category. No allocation, no indirection, no garbage collection. The bits are right there in the variable slot, whatever storage that variable is using.</p>
<h2>What a reference variable is</h2>
<p>A reference variable is different. It doesn't hold the data itself. It holds an address, a way to find an object elsewhere in memory.</p>
<pre><code class="language-java">String name = "Adetayo";
</code></pre>
<p>The variable <code>name</code> holds an address. At that address in memory, there's a <code>String</code> object containing the characters, the hash code, and the other fields that <code>String</code> maintains internally. If you assign <code>name</code> to another variable, that second variable gets a copy of the address, not a copy of the string.</p>
<pre><code class="language-java">String a = "Adetayo";
String b = a;
</code></pre>
<p>Both <code>a</code> and <code>b</code> now hold the same address. They point to the same <code>String</code> object. Setting <code>b = "Tayo"</code> doesn't modify the string that <code>a</code> points to. It replaces the address stored in <code>b</code> with the address of a different string object. <code>a</code> still points to <code>"Adetayo"</code>.</p>
<p>You can't inspect a reference's numeric value from Java code in any stable or useful way. <code>System.out.println(a)</code> calls <code>toString()</code> on the object, not on the reference. The address is internal to the JVM.</p>
<p>A reference variable can also hold a special value: <code>null</code>. <code>null</code> means the variable holds no address, so it doesn't point to any object. Calling a method on a null reference throws a <code>NullPointerException</code>, because there's no object at the end of a null to call the method on.</p>
<h2>The stack and the heap</h2>
<p>This is where the two categories connect to memory layout.</p>
<p>Each thread in a JVM process has its own <strong>call stack</strong>. The stack is divided into frames, one per active method call. A frame holds the method's local variables and its operand stack. When a method returns, its frame is gone.</p>
<p>Local variables, both primitives and references, live in the stack frame. <code>int x = 42</code> inside a method: the slot for <code>x</code> is part of the current frame. <code>String name = "Adetayo"</code> inside a method: the slot for <code>name</code> (which holds an address) is part of the current frame.</p>
<p>Objects live in the <strong>heap</strong>. The heap is shared across all threads. When you write <code>new String("Adetayo")</code>, the JVM allocates space on the heap for the new object and returns its address. That address is what goes into <code>name</code>.</p>
<pre><code class="language-java">void greet() {
    int count = 1;              // 'count' slot in this frame, holds 1
    String msg = "Hello";       // 'msg' slot in this frame, holds an address
    // The String object is on the heap, at the address stored in 'msg'
}
</code></pre>
<p>When <code>greet</code> returns, its frame disappears. <code>count</code> and <code>msg</code> vanish with it, since they were part of the frame. The <code>String</code> object on the heap is still there, but nothing references it anymore. Eventually the garbage collector will reclaim it.</p>
<h2>Why two categories instead of one?</h2>
<p>This design is a deliberate tradeoff. Primitives avoid the overhead of heap allocation and pointer indirection. If <code>int</code> were an object, every arithmetic expression would allocate a new object on the heap, increment the GC counter, and require an extra pointer dereference to get the actual value. For a loop running a million iterations, that matters.</p>
<p>The cost of this tradeoff appears in Java's generic type system: you can't use primitives as type parameters. <code>List&lt;int&gt;</code> is not valid; you have to use <code>List&lt;Integer&gt;</code>. <strong>Autoboxing</strong>, the automatic conversion between <code>int</code> and <code>Integer</code>, papers over this at the syntax level, but the heap allocation still happens. <code>Integer.valueOf(42)</code> allocates an object (or returns a cached one for small values). Wrapping a tight numeric loop in a <code>List&lt;Integer&gt;</code> incurs allocation costs that a primitive array avoids.</p>
<p>Project Valhalla, a long-running OpenJDK effort, is working toward value types that behave like objects in generics but are stored like primitives. That work is ongoing; it doesn't change how Java behaves today.</p>
<h2>Prediction exercise</h2>
<p>Given this code:</p>
<pre><code class="language-java">void example() {
    int a = 5;
    String b = "hello";
    int[] c = {1, 2, 3};
}
</code></pre>
<p>Draw what's in the stack frame when <code>example</code> is running, and what's in the heap. Which variables hold values directly, and which hold addresses? What happens to each when <code>example</code> returns?</p>
<p>Work through it before moving on. The answer to the last question, what survives the return, is the foundation for understanding how Java programs manage memory, and it comes up constantly when reasoning about object lifetimes, method parameters, and garbage collection.</p>
]]></content:encoded>
    </item>
    <item>
      <title>What happens when you run a Java program?</title>
      <link>https://unkletayo.dev/engineering/core-java/01-what-happens-when-you-run-a-java-program/</link>
      <guid isPermaLink="true">https://unkletayo.dev/engineering/core-java/01-what-happens-when-you-run-a-java-program/</guid>
      <description>What javac and java actually do: compilation to bytecode, class loading and linking, the JIT compiler, and how the call stack works, with real javap output.</description>
      <pubDate>Tue, 02 Jun 2026 07:00:00 GMT</pubDate>
      <category>java</category>
      <category>corejava</category>
      <category>jvm</category>
      <category>bytecode</category>
      <enclosure url="https://unkletayo.dev/og/engineering/core-java/01-what-happens-when-you-run-a-java-program.png" length="0" type="image/png"/>
      <media:content url="https://unkletayo.dev/og/engineering/core-java/01-what-happens-when-you-run-a-java-program.png" medium="image"/>
      <content:encoded><![CDATA[<p><img src="https://unkletayo.dev/og/engineering/core-java/01-what-happens-when-you-run-a-java-program.png" alt="What happens when you run a Java program?" /></p>
<p>You type <code>javac Hello.java</code>. A moment later, <code>Hello.class</code> appears. Then <code>java Hello</code>, and something prints to the terminal. Those two commands do very different things, and understanding exactly what each one does is the foundation everything else in Java builds on.</p>
<p>Here is the program we'll trace all the way through.</p>
<pre><code class="language-java">// Hello.java
public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}
</code></pre>
<h2>Three documents, not one</h2>
<p>Before anything else, it helps to know that "Java" is actually three separate specifications that meet at a file boundary.</p>
<p>The <strong>Java Language Specification</strong> defines what valid Java source code means. It says what <code>int x = 5</code> means, what <code>instanceof</code> does, how method overloading is resolved. It says nothing about <code>.class</code> files or how programs execute.</p>
<p>The <strong>Java Virtual Machine Specification</strong> defines an abstract stack-based machine that processes a specific binary instruction set called bytecode. It says nothing about <code>.java</code> files. It doesn't know what source code is.</p>
<p><strong>HotSpot</strong> is a concrete program, one real implementation of the JVMS abstract machine. When someone says "Java compiles to native code" or "Java is interpreted", they're describing HotSpot's behaviour, not anything the JVMS requires. A conforming JVM could interpret every instruction forever and still be correct.</p>
<p><code>javac</code> translates source code (JLS) into bytecode (JVMS). <code>java</code> runs a JVM (HotSpot) that executes the bytecode. This three-way separation explains a lot of "why does Java do that?" questions later in this series.</p>
<h2>What javac does</h2>
<p><code>javac</code> does more than translate text. It parses the source, builds an abstract syntax tree, type-checks every expression against the JLS rules, and then emits bytecode. The resulting <code>.class</code> file contains the compiled bytecode for every method, plus a constant pool, a lookup table of strings, class names, method signatures, and other constants the methods refer to by index.</p>
<p>You can inspect the result yourself:</p>
<pre><code>javac Hello.java
javap -c Hello.class
</code></pre>
<p>The <code>javap</code> tool ships with the JDK and disassembles <code>.class</code> files. The output for <code>Hello.class</code> looks like this (expected output from OpenJDK 25, your offsets will match):</p>
<pre><code>Compiled from "Hello.java"
public class Hello {
  public Hello();
    Code:
       0: aload_0
       1: invokespecial #1    // Method java/lang/Object."&lt;init&gt;":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #7    // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #13   // String Hello
       5: invokevirtual #15   // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: return
}
</code></pre>
<p>The numbers on the left are bytecode offsets in bytes, not line numbers. This is a stack machine. Instructions push values onto an operand stack and pop them off. Each method has its own operand stack and its own set of local variable slots.</p>
<p>Walk through <code>main</code> instruction by instruction:</p>
<ul>
<li><code>getstatic #7</code>: push the value of <code>System.out</code> (a <code>PrintStream</code> object reference) onto the operand stack. The <code>#7</code> is an index into the constant pool; at runtime the JVM resolves it to the actual field value.</li>
<li><code>ldc #13</code>: push the string constant <code>"Hello"</code> onto the operand stack.</li>
<li><code>invokevirtual #15</code>: call <code>println</code>. The JVM pops the <code>PrintStream</code> reference and the string off the stack, dispatches the call, and the method runs.</li>
<li><code>return</code>: exit <code>main</code>.</li>
</ul>
<p>The bytecode for <code>Hello()</code> (the constructor the compiler generated automatically) loads <code>this</code> with <code>aload_0</code>, calls <code>Object.&lt;init&gt;</code> to initialise the parent, and returns.</p>
<p>This is what your Java source actually becomes. The JVM executes these instructions, not your original text.</p>
<h2>What java does: loading and linking</h2>
<p><code>java Hello</code> starts a JVM process, which then has to get the <code>Hello</code> class ready before it can run anything. This happens in three stages.</p>
<p><strong>Loading</strong> is finding and reading the bytes. The JVM uses a chain of class loaders. The bootstrap class loader (built into the JVM, not a Java class itself) loads <code>java.lang.*</code>, <code>java.io.*</code>, and other platform classes from the JDK's own modules. The platform class loader (formerly extension class loader) handles extension modules. The application class loader loads your <code>.class</code> files from the classpath. When <code>Hello</code> references <code>java.lang.System</code>, the JVM loads <code>System</code> if it isn't already loaded. A class doesn't exist in the JVM until it has been loaded. Referencing a class name in source code is not the same as having the class available at runtime.</p>
<p><strong>Linking</strong> has three sub-stages. Verification checks that the bytecode is well-formed. Instructions are valid, type constraints are respected, and there are no stack underflows. Preparation allocates memory for static fields and sets them to default values (<code>0</code> for numeric types, <code>false</code> for <code>boolean</code>, <code>null</code> for references). Resolution replaces symbolic references in the constant pool with direct references to runtime representations. The <code>#7</code> index pointing to <code>System.out</code> gets resolved to an actual memory location.</p>
<p><strong>Initialisation</strong> runs the class's static initialiser (the <code>&lt;clinit&gt;</code> method, if any). For <code>Hello</code> there's nothing to initialise. For a class with <code>static int COUNT = 100;</code>, that assignment runs here. Static fields reach their declared values during initialisation, not during preparation (preparation only sets the default).</p>
<p>The JVM performs this sequence lazily. A class is loaded the first time something needs it, not when the program starts. That means a class with a syntax error in an unreachable branch won't necessarily cause problems until that branch is first reached.</p>
<h2>Execution: interpreter, then JIT</h2>
<p>Once <code>Hello</code> is initialised, the JVM calls <code>main</code>. The initial execution mode is interpretation. The JVM has an interpreter that reads each bytecode instruction and carries it out directly, in a loop that processes one instruction per iteration.</p>
<p>Interpretation is flexible but slow compared to native code. HotSpot watches how often each method is called. When a method becomes "hot", meaning it has been called often enough to cross a threshold, HotSpot's JIT compiler kicks in. It compiles the bytecode for that method into native machine instructions for your actual CPU. After that, calling the method runs the native code directly, skipping the interpreter entirely.</p>
<p>HotSpot has two JIT compilers. C1 (the client compiler) is fast to compile and produces moderately optimised code. It's used early for methods that are warm but not yet very hot. C2 (the server compiler) takes longer to compile but produces highly optimised native code, applying techniques like inlining, loop unrolling, and escape analysis. The same Java method can be compiled by C1 first, then recompiled by C2 as it stays hot.</p>
<p>None of this is visible to you as the programmer. The JVM decides which methods to compile, when to compile them, and whether to deoptimise and recompile if its assumptions turn out to be wrong. From the JLS's perspective, what happens at runtime is entirely the JVM's business.</p>
<p>One JIT optimisation worth knowing early: <strong>escape analysis</strong>. If the JVM can prove that an object never escapes the method that creates it, it can allocate the object on the stack frame instead of the heap. This means no garbage collector involvement and faster allocation. HotSpot does this in practice. That's why "Java objects always live on the heap" is a statement about typical HotSpot behaviour, not a JVMS guarantee.</p>
<h2>The call stack</h2>
<p>Each thread in a Java program has its own call stack. The stack is a sequence of frames. When <code>main</code> calls <code>add(3, 4)</code>, a new frame is pushed. When <code>add</code> returns, its frame is popped. The return value lands on the caller's operand stack.</p>
<p>Each frame holds:</p>
<ul>
<li><strong>Local variables</strong>: numbered slots. Slot 0 in an instance method holds <code>this</code>; in a static method slots start from the first parameter. <code>a</code> and <code>b</code> in <code>add(int a, int b)</code> are slots 0 and 1.</li>
<li><strong>Operand stack</strong>: the working area for the current instruction sequence.</li>
<li><strong>A reference to the runtime constant pool</strong> of the current class, so symbolic references can be resolved.</li>
</ul>
<p>Trace it concretely. The JVM starts executing <code>main</code>. The <code>main</code> frame is on the stack. <code>main</code> computes <code>int result = add(3, 4)</code>:</p>
<ol>
<li>The JVM pushes an <code>add</code> frame onto the stack. Slot 0 of the new frame gets the value 3; slot 1 gets 4. These are copies of the arguments, not the original storage.</li>
<li>Inside <code>add</code>, the bytecode loads slot 0 (<code>iload_0</code>), loads slot 1 (<code>iload_1</code>), executes <code>iadd</code>, and returns the result with <code>ireturn</code>.</li>
<li>The <code>add</code> frame is popped. The return value 7 is pushed onto <code>main</code>'s operand stack. <code>main</code> stores it in its local variable for <code>result</code>.</li>
</ol>
<p>The stack is bounded in size. If you write a method that calls itself without ever reaching a base case, the JVM keeps pushing frames until it runs out of stack space. The result is a <code>StackOverflowError</code>. This isn't specific to recursive methods. A chain of a thousand non-recursive method calls deep enough would have the same effect, just far less likely in practice.</p>
<h2>Prediction exercise</h2>
<p>Before running: what do you expect <code>javap -c</code> to show for the following program?</p>
<pre><code class="language-java">public class Add {
    public static void main(String[] args) {
        int a = 3;
        int b = 4;
        int c = a + b;
        System.out.println(c);
    }
}
</code></pre>
<p>Specifically, how many bytecode instructions appear between the start of <code>main</code> and the <code>invokevirtual</code> for <code>println</code>? And which instructions handle the local variables <code>a</code>, <code>b</code>, and <code>c</code>?</p>
<p>Compile it, run <code>javap -c Add.class</code>, and check. The instructions you see, <code>iconst_3</code>, <code>istore_1</code>, <code>iload_1</code>, <code>iadd</code>, and so on, reveal how the JVM's stack-based architecture handles local variables and arithmetic. Each instruction's name encodes its type (<code>i</code> for int, <code>a</code> for reference) and what it does. Once you can read a few lines of bytecode, the JVM's execution model stops being abstract.</p>
]]></content:encoded>
    </item>
  </channel>
</rss>
