Immutability of Strings
1. What Immutable Means (beginner)
Immutable = once built, a String object never changes. Every "edit" (+, replace, trim) secretly builds a brand-new String, old one becomes garbage. Like printed book: can't edit page, must reprint!
2. Proof Code (see new objects!)
String s = "hi";
System.out.println(System.identityHashCode(s)); // e.g. 111 (address!)
s = s + "!"; // NOT edited — NEW object "hi!" created, s now points there!
System.out.println(System.identityHashCode(s)); // e.g. 222 (DIFFERENT!)
System.out.println(s); // hi! (s moved, old "hi" garbage!)
String t = "hello";
t.toUpperCase(); // returns "HELLO" but THROWN AWAY!
System.out.println(t); // still hello (unchanged — trap!)
t = t.toUpperCase(); // MUST assign back!
System.out.println(t); // HELLO (correct!)
3. Why Java Did This (exam reasons!)
- Security:
"password"can't be secretly altered (safe keys, URLs). - Pool sharing: literals share one copy (saves memory — safe because no one can change it!).
- Thread-safe: many threads read same String, no locks needed.
4. Cost + Fix
Loop s += i 10,000× = 10,000 garbage objects (slow!). Fix: StringBuilder/StringBuffer (mutable, next topics!).
5. Exam Points
- Define + proof (
hashCodechanges,tunchanged) — 5-7 marks, very frequent. - Why immutable (security/pool/threads) + loop cost — 5 marks, frequent.