Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Why are strings often immutable? What problems does mutability cause?

FresherFundamentalsOOP & Language Fundamentals
Model answer

Why strings are immutable

Immutable strings cannot change after creation—operations return new strings. Benefits: thread safety, safe sharing as map keys, string interning; JVM can optimize literals.

  • Security: Password strings not cleared if mutable.
  • Hashing: hashCode cached safely for HashMap keys.
  • Pitfall: Concatenating in a loop—use StringBuilder.
java
String a = "hi";
a = a + "!"; // new object; original "hi" unchanged
Contrast with mutable StringBuilder for hot loops.