Fundamentals · Medium · Free
Why are strings often immutable? What problems does mutability cause?
FresherFundamentalsOOP & Language Fundamentals
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" unchangedContrast with mutable
StringBuilder for hot loops.