Why are Strings Immutable in Java?
Learn why Strings are immutable in Java, how the final class and String pool enforce it, and the thread-safety, security and hashCode benefits with examples.
Expected Interview Answer
Strings are immutable in Java because a String object's character contents can never change after it is created; any operation that appears to modify a String actually returns a brand-new String object.
Immutability is enforced by making the String class final, storing the characters in a private final array, and never exposing that array. This design enables the String pool (interning), makes Strings safe to share across threads without synchronization, guarantees a stable hashCode for use as HashMap keys, and protects security-sensitive values like class names, file paths, and network hosts from being altered after validation.
- Enables the String pool to save memory by reusing literals
- Thread-safe by design with no synchronization needed
- Safe to cache the hashCode, speeding up HashMap and HashSet
- Prevents tampering with security-sensitive values after checks
- Safe to share references freely without defensive copies
AI Mentor Explanation
A completed scorecard for a finished innings is fixed history: once the innings ends you cannot rewrite a batter's score on it. If you want a corrected version you print a fresh scorecard, leaving the original untouched. A Java String behaves the same way — you never edit it, you produce a new one.
Step-by-Step Explanation
Step 1
Class is final
The String class is declared final, so no subclass can override behavior to expose or mutate the internal characters.
Step 2
Private final storage
Characters are held in a private final byte/char array that is never handed out to callers.
Step 3
No mutators
String provides no method that alters existing content; methods like concat, replace and toUpperCase return new String objects.
Step 4
String pool reuse
Because content cannot change, identical literals can safely be interned and shared from the pool to save memory.
Step 5
Cached hashCode
The hashCode is computed once and cached, which is only safe because the content never changes.
What Interviewer Expects
- A clear definition of immutability
- The mechanisms that enforce it (final class, final array, no mutators)
- Why the String pool depends on immutability
- Thread-safety and hashCode-caching benefits
- Security motivation for immutable Strings
Common Mistakes
- Claiming methods like replace() modify the original String
- Confusing immutability with the reference being final
- Saying String is thread-safe because it is synchronized
- Not mentioning the String pool as a reason for immutability
- Believing a large loop of concatenation mutates one String
Best Answer (HR Friendly)
“In Java, once you create a piece of text it can never be changed; if you modify it, Java quietly makes a fresh copy and leaves the original alone. This makes text safe to share between different parts of a program and helps the language reuse memory efficiently.”
Code Example
String s = "Hello";
s.concat(" World"); // return value ignored
System.out.println(s); // still prints: Hello
String t = s.concat(" World"); // new String captured
System.out.println(t); // prints: Hello World
// Interned literals share the same object
String a = "java";
String b = "java";
System.out.println(a == b); // true - same pooled objectFollow-up Questions
- How does the String pool (interning) work and when should you use intern()?
- Why is a StringBuilder preferred for concatenation inside a loop?
- How does immutability make String safe as a HashMap key?
- Can reflection break String immutability, and what are the risks?
- Why are immutable objects inherently thread-safe?
MCQ Practice
1. What does s.replace('a', 'b') return when s is unchanged text?
String methods never mutate the original; replace() returns a brand-new String with the changes applied.
2. Which feature is directly enabled by String immutability?
Because content cannot change, identical literals can be safely interned and shared through the String pool.
3. Why can String safely cache its hashCode?
A cached hashCode is only valid if the underlying content is guaranteed never to change, which immutability guarantees.
Flash Cards
Is String immutable in Java? — Yes. Its contents cannot change after creation; modifying operations return new String objects.
What enforces String immutability? — The class is final, the character storage is private and final, and no method mutates it.
Why is String thread-safe? — Immutable objects have no changeable state, so multiple threads can share them without synchronization.
How does immutability help HashMap? — A String key's hashCode never changes, so it can be cached and the key stays findable in the bucket.