Java · OOP, JVM and backend craft
Why is String immutable in Java?
Short answer
String is immutable: its value cannot change after construction. That makes it safe to share, cache hash codes, use in the string pool and pass across threads without copying.
String is final and exposes no mutators. Internally it stores the characters in a final byte array with a compact-string encoding flag. Every apparent change, such as concatenation or toUpperCase, returns a new String rather than modifying the original.
String original = "java";
String upper = original.toUpperCase();
System.out.println(original);
System.out.println(upper);Why the design pays off
- String literals can be shared safely in the string pool
- The hash code can be computed once and cached for use as a HashMap key
- Immutable values are inherently thread-safe and can be shared freely
- Security-sensitive values such as class names and paths cannot be changed underneath a check
Immutability also has costs. Concatenating in a loop creates many intermediate objects, and sensitive values remain in the heap until collected. For large data, a char array or stream may be more appropriate. For repeated concatenation, use StringBuilder.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the string pool?
- 2Why does String cache its hash code?
- 3When is String a bad choice for sensitive data?
- 4How does concatenation in a loop affect memory?
Say it in the interview
String is immutable because its internal value is final and there are no mutating methods. That lets the JVM share literals in the string pool, cache the hash code and treat strings as thread-safe. Any operation like toUpperCase returns a new object. The trade-off is allocation churn when concatenating repeatedly, so I use StringBuilder for loops and avoid assuming that double equals compares content.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Java mock interview and get scored feedback on depth, clarity and confidence.