HuntExams Academy logo
JavaIntermediate#strings

Why are Strings immutable in Java?

Answer

Security (used as DB URLs, classloader keys), thread safety, String pool reuse to save memory, and reliable hashCode caching for HashMap keys.

Example

String a = "cat";
String b = "cat";
// both point to same object in the String pool since Strings are immutable & interned

Detailed explanation

A String in Java is immutable: once constructed, its sequence of characters cannot change. Methods such as concat(), replace(), and toUpperCase() return a result rather than modifying the original object; they may return the same instance when no change is needed. Reassigning a String variable changes which object the variable references, not the contents of the old object. This distinction matters because immutability is a property of the object, whereas final on a variable only prevents reassignment of that reference.

Immutability makes sharing Strings safe and enables string-pool reuse. In String a = "cat"; String b = "cat";, both variables reference the same interned literal, so a == b is true. Because neither reference can modify that object, sharing cannot unexpectedly affect another caller. However, not every String is automatically interned: new String("cat") creates a distinct String object, while intern() obtains its canonical pooled representation. String is final, its backing storage is private, and its public API does not expose mutable internal storage. Modern OpenJDK implementations generally use a byte array with an encoding indicator; older implementations used a char array.

Security and concurrency are further reasons. Strings frequently represent database URLs, file paths, and class names used during class loading. If a validated value could be changed through another reference before use, code might act on different data from what it checked. Immutability prevents that particular risk, although it does not replace validation or access controls. Multiple threads can also read the same String without coordinating changes to its contents. This does not make a shared variable holding a String, or a larger operation involving it, automatically thread-safe.

Finally, immutable contents give Strings stable equality and hash codes. A String can cache its computed hash code and reuse it, benefiting repeated hash-based lookups. More importantly, its hash and equality behaviour cannot change after insertion into a HashMap, making it a reliable key. Interviewers generally expect you to connect these benefits to safe sharing and stable values, rather than merely list security, pooling, and thread safety as unrelated keywords.

Key points to remember

  • String immutability means its character sequence never changes after construction.
  • Immutable contents prevent a validated String from being altered through another reference.
  • Threads can safely share String contents, but shared-reference updates may still require coordination.
  • Interned literals share one canonical object; not all Strings are automatically interned.
  • Stable equality and hash codes make Strings reliable HashMap keys and allow hash-code caching.

Common mistakes candidates make

  • Confusing an immutable String object with a final variable, which only prevents reference reassignment.
  • Claiming every String is pooled or using == instead of equals() to compare contents.
  • Saying final alone guarantees immutability; backing storage must also be protected from mutation.

Likely follow-up questions

What happens when we write s = s + "x"?

Java computes the concatenated value and assigns the resulting reference to s; the original String remains unchanged. For repeated concatenation in a loop, StringBuilder usually avoids creating many intermediate results.

Why is String declared final?

Declaring String final prevents subclasses from overriding methods in ways that violate its expected behaviour. Final is only part of the design: private storage and the absence of mutating APIs are also essential.

Why are mutable objects risky as HashMap keys?

If fields used by equals() or hashCode() change after insertion, a lookup may search a different bucket or fail to match the stored key. String avoids this problem because its equality-relevant contents cannot change.

Interview tip: Start with the object-versus-reference distinction, demonstrate literal sharing with the "cat" example, and connect immutability to security, concurrency, pooling, and stable hashing.

Related Interview Questions

1
JavaIntermediate#collections

Explain the Collections framework hierarchy.

Open
2
JavaBeginner#collections#list

ArrayList vs LinkedList?

Open
3
JavaIntermediate#collections#concurrency

HashMap vs Hashtable vs ConcurrentHashMap?

Open