Why is the String class immutable in Java?
Once created, a String cannot change. This makes the string pool safe to share, lets the hash code be cached for fast HashMap use, keeps strings thread-safe, and stops callers from altering values used for security, such as file paths or URLs.
Explain it simply
A String is like a printed railway ticket. If the name could be changed after printing, the TTE could never trust it. Because it cannot be altered, many people can safely hold the same ticket, and everybody sees the same details.
Example
String s = "Ravi";
s.concat(" Kumar"); // result is thrown away
System.out.println(s); // prints: Ravi
s = s.concat(" Kumar"); // new String, s now points to it
System.out.println(s); // prints: Ravi KumarWhat to say in the interview
"String is final and its internal data cannot be changed, so every operation like concat or toUpperCase returns a new object. That allows four things. The string pool can reuse one object for many references. The hash code is computed once and cached, which makes Strings excellent HashMap keys. Strings are automatically thread-safe. And security-sensitive values like a database URL cannot be modified after validation."
Common mistakes
- Thinking
s.concat("x")changess. - Saying immutability means the variable cannot be reassigned. That is
final, not immutable.