Java String Interning, Identity, and Concatenation Costs
StringsModel answerLast updated
Trace identity vs equality across literals, `new String`, `intern`, and constant folding, then compare loop `+`, `StringBuilder`, and `StringBuffer`.
Strings in Java raise three recurring concerns: where the object lives in memory, when two references point at the same object, and how much work concatenation costs.
Part 1 — Layout and identity
Consider:
String s1 = "data";
String s2 = "data";
String s3 = new String("data");
String s4 = s3.intern();
String s5 = "da" + "ta";
String prefix = "da";
String s6 = prefix + "ta";
Answer the following:
- For each pair —
(s1, s2),(s1, s3),(s1, s4),(s1, s5),(s1, s6)— say whether==is true and whetherequalsis true, and justify each. - Describe where each resulting object lives (ordinary heap vs. the string constant pool) and explain precisely what
s3.intern()does. - Explain why
s5ands6behave differently, in terms of compile-time constant folding versus runtime evaluation. Also state what changes ifprefixis declaredfinal.
Part 2 — Building strings
Compare three ways to assemble a string incrementally:
- repeated
+inside a loop, StringBuilder,StringBuffer.
Cover time and memory behavior, thread safety, and practical guidance. Then explain how non-loop concatenation is compiled in Java 9+ (invokedynamic / StringConcatFactory) and identify the situations where you still must reach for StringBuilder yourself.
Hints
Hint 1
Distinguish what the compiler can decide at compile time from what must wait until runtime; a variable being `final` matters more than it looks.
Hint 2
Think about what `new` guarantees compared to what a literal guarantees, and what `intern()` returns for a value that already exists in the pool.
Hint 3
For the loop comparison, count how many characters get copied in total when you append n pieces to an immutable string versus a growable buffer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Identity, equality, and memory
A string literal, and any expression the compiler can fully evaluate at compile time, is interned: all occurrences of the same value collapse to a single canonical String object. The JVM keeps a table (the StringTable) of these canonical strings. new String(...) is the exception: it always allocates a fresh object.
| Pair | == | equals | Why |
|---|---|---|---|
(s1, s2) | true | true | Both literals resolve to the same pooled instance. |
(s1, s3) | false | true | new always creates a distinct heap object. |
(s1, s4) | true | true | intern() returns the already-pooled instance, which is the one s1 holds. |
(s1, s5) | true | true | "da" + "ta" is a constant expression, so javac folds it into the literal "data". |
(s1, s6) | false | true | prefix is a plain (non-final) variable, so the join happens at runtime and produces a new, unpooled object. |
Memory state (Java 7 and later). The pool is no longer a separate PermGen region; pooled strings are ordinary heap objects referenced from the native StringTable. So:
- One pooled
"data"object;s1,s2,s4, ands5all reference it. s3is a separate heap object. In modern JDKs theString(String original)constructor copies the reference to the backingbyte[]rather than duplicating the characters, sos3is a distinct object that typically shares storage with the pooled"data". Mentioning this is a good signal."da"is itself a literal, so it is pooled, andprefixreferences it.s6is a freshly allocated, unpooled heap string, collectible once unreachable.
What s3.intern() does. The JVM hashes the value and looks it up in the StringTable. If a match exists, that canonical reference is returned — here the same object s1 points to, so s4 == s1. If no match existed, the JVM would register s3 itself as canonical and return s3 (this is the Java 7+ behavior; pre-7 it copied the characters into the permanent generation). That last detail is why interning a long-lived string from a short-lived object can surprise people: the original object may become the one that stays alive.
Why s5 and s6 differ. "da" + "ta" consists entirely of compile-time constants, so javac emits a single ldc of "data", and the language guarantees that constant string expressions are interned. prefix is an ordinary local variable, so the compiler cannot know its value and emits runtime concatenation code, whose result is never automatically interned. Making it final String prefix = "da"; turns it into a constant variable; the expression then folds, and s6 == s1 becomes true.
Note that s1.equals(s6) is true and s1 == s6.intern() is true in all cases — interning reconciles identity with value.
Part 2 — Construction trade-offs
| Pattern | Time | Allocations | Thread safety |
|---|---|---|---|
+ in a loop | O(n·L) — quadratic in output size | A new string (plus a temporary buffer) every iteration, heavy GC churn | Immutable result, but rebuilt each pass |
StringBuilder | Amortized O(L) | One growable buffer (default capacity 16, grows roughly 2×+2); pre-size when the length is known | Not synchronized |
StringBuffer | Amortized O(L) plus a lock on every call | Same as StringBuilder | Methods synchronized |
The loop problem. Each s = s + piece copies all previously accumulated characters because the right-hand side must produce a brand-new immutable string. Over n pieces of average length L, total copying is quadratic. A builder appends in place and only occasionally reallocates and copies its buffer, giving linear amortized cost and O(L) space.
Choosing. Default to StringBuilder for incremental assembly, and pass an initial capacity when you can estimate it. StringBuffer is a legacy class: method-level locking is costly and rarely meaningful, since multi-step operations still need external coordination, and builders are almost always confined to one thread. With biased locking disabled in newer JDKs, even uncontended locking is not free.
Java 9+ non-loop concatenation. For an expression like a + b + c outside a loop, javac emits an invokedynamic instruction whose bootstrap method is StringConcatFactory.makeConcatWithConstants, along with a recipe string in which \u0001 marks argument slots and literal text is embedded. On first execution the call site links a MethodHandle strategy that computes the exact final length and encoding up front, allocates the result array once, and copies directly into it — no intermediate builder, no resizing. Because the strategy lives in the JDK, it can improve without recompiling caller bytecode.
When you still need StringBuilder manually:
- Inside loops — each iteration is a separate concatenation;
indycannot fuse across iterations. - When you accumulate across statements, branches, or method calls (conditional appends, passing a builder to helpers).
- When the output is large and you want to pre-size to avoid regrowth.
Complexity and edge cases
Loop + costs O(n·L) time and O(n·L) total allocation; StringBuilder costs O(L) amortized time and O(L) space. Watch for:
null + "x"yields"nullx"rather than throwing.- Using
==on strings from input, deserialization, orsubstringis almost always a bug — useequals. 'a' + 'b' + "c"is"195c": the twochars are promoted tointand added before any string concatenation begins.
StringBuilder sb = new StringBuilder(estimatedLength);
for (String part : parts) sb.append(part);
String result = sb.toString();