medium.com 7 min read Original Source

Two Strings Walked Into an if Statement. Only One of Them Was Real.

Somewhere in a login flow, a comparison like if (role == "admin") sat quietly for months, working every time, because in that codebase the value always arrived as a literal. Then someone changed the upstream code so the role came back built from pieces, region + "_admin" at runtime instead of typed by hand, and the comparison started failing silently. Same characters. Same length. Same everything a human eye could check. The if said no anyway.

Nothing there was broken, really. The comparison was doing exactly what == has always done on objects, i.e. asking whether two references point at the same physical thing in memory, not whether the things they point at look alike. The bug wasn’t in the logic. It was in a quiet assumption about what a string actually is in Java, one that most people absorb wrong early and never quite get corrected.

The pool: one room where certain strings are made to live together

When the compiler encounters a string literal, "admin" written directly into source code, it doesn’t just drop a fresh object onto the heap and move on. It checks a special reservoir called the string constant pool first. If an identical literal has already been interned there by anything else the class has loaded, the compiler hands back a reference to that existing object rather than minting a new one. Write "admin" in two completely unrelated files, and at runtime both end up pointing at the exact same object, the same address, the same everything. This is why "admin" == "admin" returns true even across files that have never heard of each other: they were never two different strings to begin with, only two names for one.

This pool used to live in a region called PermGen, a separate slice of memory the JVM reserved for class metadata. Since Java 7, it moved into the ordinary heap, alongside every other object, which mattered less for how it behaves than for how it’s tuned and garbage collected, but it’s worth knowing the history if the topic ever comes up, because plenty of older material still describes PermGen as if it were current.

Compile-time constant folding extends this further than most people expect. "ad" + "min", written with both halves as literals, is evaluated entirely by the compiler before your program ever runs, folded into the single literal "admin", and interned exactly as if you’d written it that way from the start. The moment either side of that concatenation is a variable rather than a literal, prefix + "min", the folding can no longer happen at compile time, because the compiler has no way of knowing what prefix will hold until the program actually runs. Since Java 9, that runtime concatenation compiles down to an invokedynamic call into StringConcatFactory rather than the explicit chain of StringBuilder.append() calls javac used to emit, but the outcome that matters here hasn’t changed: a string built at runtime is a freshly forged object, and it does not, on its own, live in the pool.

String a = "admin";
String b = "admin";
System.out.println(a == b); // true — same pooled object
String prefix = "ad";
String c = prefix + "min";
System.out.println(a == c); // false — built at runtime, not the same object
String d = new String("admin");
System.out.println(a == d); // false — explicitly forced onto the heap, outside the pool
String a = "admin";
String b = "admin";
System.out.println(a == b); // true — same pooled object
String prefix = "ad";
String c = prefix + "min";
System.out.println(a == c); // false — built at runtime, not the same object
String d = new String("admin");
System.out.println(a == d); // false — explicitly forced onto the heap, outside the pool

new String("admin") is the most direct way to see this, and it’s a useful thing to have memorized precisely because it’s the opposite of what most people expect the first time they see it. Even though the literal "admin" inside that constructor call is itself pooled, wrapping it in new String(...) explicitly manufactures a second, independent object on the heap that merely copies the pooled one’s contents. Two objects, same characters, different addresses. == sees the addresses. equals() sees the characters. This is the entire reason the rule exists: always compare strings with .equals() unless you have a specific, deliberate reason to be asking about identity rather than content, and role == "admin" is essentially never that reason.

If you genuinely need a runtime-built string to be treated as identical, by reference, to its pooled counterpart, String.intern() does exactly that: it looks the string’s contents up in the pool and hands back the canonical pooled reference if one already exists, adding it to the pool if it doesn’t. It’s rarely the right tool for ordinary application code, since .equals() already solves the comparison problem without touching identity at all, but it’s worth knowing it exists, particularly for memory-sensitive situations where deduplicating a large number of runtime-built strings with repeated content, log tags, category names, that sort of thing, genuinely saves meaningful heap space.

Why immutability isn’t a side detail here. It’s the whole reason any of this is safe.

Sharing only works if nothing sharing the object can quietly change it out from under everything else holding the same reference. If strings were mutable, the entire pool would be a minefield: mutate the string behind one reference to "admin", and every other piece of code anywhere in the JVM holding what it believed was its own private copy of "admin" would watch its value change without warning, because there was never more than one object to begin with. Pooling is the optimization. Immutability is the precondition that makes the optimization safe to attempt at all.

This same property answers questions that seem, at first, to have nothing to do with pooling. Strings are inherently thread-safe with zero synchronization, because there is no mutation to race over, no partial write another thread could ever observe halfway through. A String used as a HashMap key can have its hash code computed once and cached forever in a private field the object carries internally, something that would be a correctness hazard for a mutable key, exactly the mutable-key trap this series covered when discussing HashSet and HashMap more generally, except here the language sidesteps the entire category of bug by design rather than leaving it to caller discipline. And there’s a security dimension too, less discussed but genuinely load-bearing: file paths, URLs, and class names are routinely represented as strings, validated once and then acted on, and if strings could be mutated after that validation but before use, a malicious or merely careless piece of code sharing a reference could rewrite the value in the gap between the check and the action, a class of bug with an actual name, time-of-check to time-of-use. Immutability closes that gap categorically, not through discipline, but because there’s nothing there to rewrite.

How the object actually keeps its promise

For a long time, a String stored its characters in a plain char[], and substring() was implemented as a genuine shortcut: rather than copying characters into a new array, the substring shared the original array and simply recorded a different offset and length into it. This was clever and fast, and it was also a quiet memory leak waiting to happen. Extract a three-character substring from a ten-megabyte string, and as long as anything held a reference to that tiny substring, the entire ten-megabyte backing array stayed alive, pinned in memory by three characters someone actually needed. Java 7 update 6 changed substring() to copy the relevant characters into a fresh, appropriately sized array instead, trading a small amount of extra copying for the elimination of an entire category of accidental memory retention.

Java 9 changed the internal representation again, more substantially. Rather than a char[], where every character costs two bytes regardless of content, a String now stores a byte[] alongside a single coder flag indicating whether the content is representable in Latin-1, one byte per character, or needs the full UTF-16 encoding, two bytes per character. The overwhelming majority of strings in a typical Java program, identifiers, English text, JSON keys, numbers rendered as text, fit entirely within Latin-1, and this change, called Compact Strings, cut their memory footprint roughly in half without changing a single line of code anyone using String had to write. It’s a good example of the kind of improvement that never shows up in a tutorial precisely because nothing about the public API changed, only what’s sitting quietly underneath it.

The mutable escape hatch, used on purpose

None of this means concatenation is forbidden, only that repeated concatenation of an immutable type has a real cost worth understanding rather than working around by accident. Every += on a String inside a loop constructs an entirely new object each time, copying everything accumulated so far plus whatever’s being appended, which makes a loop of that shape quadratic in the total length of the result, not linear. StringBuilder exists precisely to opt back into mutability on purpose, for exactly the situations where you know you’re going to build something up incrementally and don’t want a fresh, fully-copied object at every step:

// Quadratic: recreates the entire string on every iteration
String result = "";
for (String word : words) {
    result += word;
}

// Linear: one mutable buffer, resized only when it runs out of room
StringBuilder result = new StringBuilder();
for (String word : words) {
    result.append(word);
}
String finalResult = result.toString();
// Quadratic: recreates the entire string on every iteration
String result = "";
for (String word : words) {
    result += word;
}

// Linear: one mutable buffer, resized only when it runs out of room
StringBuilder result = new StringBuilder();
for (String word : words) {
    result.append(word);
}
String finalResult = result.toString();

StringBuilder‘s own internal buffer is a genuinely mutable, resizable array, exactly the thing String deliberately refuses to be, and reaching for it when you know you’re accumulating text isn’t a workaround, it’s the tool the standard library built for precisely this job.

What to actually carry out of this

If an interviewer asks why String is immutable, the strongest answer touches all three legs at once rather than picking one: pooling and the memory savings it enables are only safe because nothing can mutate a shared instance out from under everything else referencing it; thread safety follows for free, with no locking required, because there’s no mutation to race over; and security-sensitive uses, paths, URLs, credentials, class names, stay valid between the moment they’re checked and the moment they’re used, because the value physically cannot change in between. And if the question is narrower, when does == behave correctly on strings, the honest answer is: only when you can prove both sides came from the pool, which in practice means literals and nothing else, and since that’s rarely something calling code can verify at a glance, .equals() should be the default reflex every time, with == reserved for the rare moment you’re deliberately asking about identity rather than content.

If you’re curious how these same identity and immutability questions play out on the Rust side, that’s the whole premise of the book I’ve been writing: every classic data structure built once in Rust and once in Java, side by side, so you can see exactly where each language’s rules force a different decision. Ownership vs. Reference: Data Structures and Algorithms in Rust and Java

For the Rust foundations that series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample