KatInterview

Java String Interning, Identity, and Concatenation Costs

StringsModel answer
MediumModel answerStringsjavastring-poolimmutability

Last 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:

  1. For each pair — (s1, s2), (s1, s3), (s1, s4), (s1, s5), (s1, s6) — say whether == is true and whether equals is true, and justify each.
  2. Describe where each resulting object lives (ordinary heap vs. the string constant pool) and explain precisely what s3.intern() does.
  3. Explain why s5 and s6 behave differently, in terms of compile-time constant folding versus runtime evaluation. Also state what changes if prefix is declared final.

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.