Java · OOP, JVM and backend craft

Why is String immutable in Java?

Mediumstringimmutabilitystring poolUpdated Oct 2026
Quiz this track

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.

java
String original = "java";
String upper = original.toUpperCase();

System.out.println(original);
System.out.println(upper);
original is unchanged. upper is a separate object.

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.

new String("text") always creates a distinct object, while a literal may reuse the pool. Do not rely on == for string content; use equals.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the string pool?
  2. 2Why does String cache its hash code?
  3. 3When is String a bad choice for sensitive data?
  4. 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.