What does it mean that String is immutable in Java, and why was it designed that way?
answer
- Contents fixed for life — no in-place edit
- final class, final byte[] value, no exposed array
- replace/substring RETURN new String
- Enables pool sharing, thread-safety, cached hash, security
- StringBuilder for heavy building
basics
~20 sAn immutable String can never change after it is created. Methods like concat or replace do not edit the original; they build and return a brand-new String. Java made String immutable for safety, sharing, and speed.
solid answer
~40 sImmutability means a String's character contents are fixed for the object's whole life: there is no method that mutates the existing instance in place. Every transforming operation (concat, substring, replace, toUpperCase) returns a new String and leaves the original untouched. Java chose this for several reasons: it lets the JVM safely share identical literals in the String pool (saving memory), it makes Strings automatically thread-safe so they can be passed around without locks, it lets the hash code be computed once and cached (great for HashMap keys), and it improves security since values like file paths, URLs, and class names cannot be altered after a check. The cost is that heavy string-building creates many throwaway objects, which is why StringBuilder exists.
go deeper
Can state that a String never changes and that methods return new strings; recognizes the throw-away-result bug.
Explains the concrete benefits (pool sharing, thread safety, cached hash, security) and knows to use StringBuilder for building.
Ties immutability to the final class + final non-exposed array, the interning pool, and the hashCode caching contract for map keys.
Discusses the security/time-of-check trade-offs, GC/allocation pressure implications, and when to defensively copy vs rely on immutability in API design.
## What 'immutable' means An object is **immutable** when its observable state cannot change after construction. For `String`, the 'state' is the sequence of characters it holds. Once you write `String s = "hello";`, that particular String object will represent `hello` forever. There is no method anywhere on `String` that turns it into `world`. Internally a String wraps an array of bytes/chars (`private final byte[] value;` in modern JDKs). Two things make it immutable: the field is `final` (the reference can't be reassigned) and the class never exposes that array, so no outside code can poke at it. The `String` class itself is also `final`, so you can't subclass it and add a mutating method. ## 'But replace() changed my string!' — no, it didn't Beginners often think this mutates: ```java String s = "hello"; s.replace('h', 'j'); // result is THROWN AWAY System.out.println(s); // still prints hello ``` Every transforming method **returns a new String**. The original is untouched. To 'change' a string you must reassign the variable to the new object: `s = s.replace('h','j');`. The variable now points at a different object; the old `hello` object is unchanged (and becomes garbage if nothing else refers to it). ## Why Java designers chose immutability 1. **String pool / interning.** Java keeps a pool of unique String literals. Because they can't change, the JVM can safely hand the *same* object to every `"hello"` literal in your program, saving memory. If Strings were mutable, one piece of code editing the shared object would corrupt every other user of it. 2. **Thread safety for free.** An object that never changes can be read by many threads simultaneously with zero synchronization, because there is no write to race against. 3. **Cached hash code.** `String` computes its `hashCode()` once and stores it. This is only safe because the contents never change. It makes Strings excellent `HashMap`/`HashSet` keys — the key's hash and equality are stable, so an entry can never get 'lost' in the wrong bucket. 4. **Security.** Strings carry sensitive values: file paths, hostnames, DB connection strings, class names passed to the class loader. If a String could mutate after a security check passed, an attacker could swap the value between the check and its use (a time-of-check/time-of-use bug). Immutability closes that hole. 5. **Safe to share / pass.** You can return a String or pass it to untrusted code without making a defensive copy, knowing the caller can't alter your copy. ## The trade-off The downside is **object churn**: building a string in a loop with `+` creates a new object each iteration, all but the last becoming garbage. That's why Java provides the *mutable* `StringBuilder`/`StringBuffer` for assembling text, and why the compiler often rewrites simple `+` concatenations for you.
- If I do s = s + "!", did the original String change?No. A new String containing the concatenation is created and s is reassigned to point at it. The original object is unchanged and becomes eligible for garbage collection if nothing else references it.
- How would you build a String efficiently in a loop?Use a StringBuilder, append in the loop, and call toString() once at the end, avoiding a new String per iteration.
saying these in an interview costs you the question
- Saying replace()/substring() modify the original string
- Thinking reassigning a variable mutated the old object
- Claiming immutability means you can never 'change' a string variable
- Confusing String immutability with the variable being final