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

Why must String be immutable, and what would break if it weren't?

Level II · JuniorStrings, StringBuilder & String Pool
Short answer

Immutability is what makes String safe to share freely, cache via the pool, and use as a HashMap key with a stable hashCode.

Explanation

If Strings were mutable, a value used as a map key or in a security check (a file path or class name) could be changed after validation — a serious time-of-check-to-time-of-use vulnerability — and the pool's sharing would let one holder corrupt another's data. Immutability also makes Strings inherently thread-safe with no synchronization.

Common mistakes
  • Saying immutability exists only for performance.
  • Forgetting its role in security, caching hashCode and thread safety.

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