Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Strings, StringBuilder & String Pool

Explain the String pool (string interning) and when intern() actually helps versus hurts.

Level III · MidStrings, StringBuilder & String Pool
Answer

String literals are interned into a pool so identical literals share one instance, which is why "a" == "a" is true but new String("a") == "a" is false. intern() lets you canonicalize runtime-built strings into the pool, which can save memory when you have massive numbers of duplicate strings (e.g., parsed tokens). But interning has CPU cost and historically lived in PermGen/now the heap-resident pool; over-interning long-lived unique strings just bloats the pool, so it's a targeted optimization, not a default.

Common mistakes
  • Calling intern() on every string, bloating the pool.
  • Saying new String("x") == "x" is true.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Strings, StringBuilder & String Pool.

Practise free

More on Strings, StringBuilder & String Pool