Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Why is String immutable in Java? Give at least four concrete benefits and one cost.

String is immutable so that a String value, once created, can be trusted everywhere it goes. That gives at least four concrete benefits: the same instance can be shared by many threads and callers without copying or locking, its hash code can be cached so String keys are cheap in a HashMap, values checked once such as file paths or class names cannot change after the check, and the string pool can share literals safely. The cost is that every modification creates a new object, so code that edits text repeatedly, for example in a loop, should use StringBuilder.

Why this question is asked

Strings are everywhere in Java: keys in maps, names of classes, URLs, SQL, JSON and log messages. Because they are so central, the decision to make them immutable shapes performance, security and concurrency across the whole platform. Interviewers ask this because many candidates can say String is immutable but cannot explain what that buys, or what it costs. In this answer, we will recap what immutability means for String, go through four benefits with code for each, look at the cost and how StringBuilder addresses it, and answer whether the final keyword on the class matters.

1A Quick Recap: What Immutable Means for String

An object is immutable when its state cannot change after it is constructed. For String, that means the characters are fixed for the lifetime of the object. Methods that look like they change a string, such as toUpperCase, replace or concat, actually return a new String and leave the original untouched.

Inside, a String holds its characters in a private final byte array (since Java 9, with a coder field that says whether it is stored as Latin-1 or UTF-16), and no method ever writes to that array after construction. The class is final, so nobody can write a subclass that adds a way to change it.

Java
String s = "java";
String t = s.toUpperCase();
System.out.println(s); // java: the original is unchanged
System.out.println(t); // JAVA: a new object

2Benefit 1: Safe Sharing Without Copies or Locks

Because a String can never change, any number of threads can read the same instance at the same time without synchronisation, and any method can keep a reference to a String it was given without making a defensive copy. If String were mutable, every class that stored a name or an id would have to copy it on the way in and on the way out, or risk a caller changing it later.

Java
class User {
private final String name;
User(String name) { this.name = name; } // no copy needed: nobody can change it
String name() { return name; } // safe to hand out
}
// compare with a mutable type, where we must copy:
// this.tags = new ArrayList<>(tags);

Notice the contrast in the last comment. For a List we have to copy defensively, because the caller still holds a reference and could add to it. With String the problem cannot arise, so code is simpler and faster.

3Benefit 2: The Hash Code Can Be Cached

A HashMap calls hashCode() on a key every time we put or get. For a String, computing the hash means walking through every character. Since the characters never change, the hash never changes either, so String computes it once and stores it in a private field. Every later call returns the stored value. That is a large part of why String is such a good HashMap key: after the first call, hashing is almost free, no matter how long the string is.

Java
String key = "a fairly long configuration key used on every request";
int h1 = key.hashCode(); // computes from all characters, then stores the result
int h2 = key.hashCode(); // returns the stored value, no work
System.out.println(h1 == h2); // true

Notice that this is only safe because of immutability. If the characters could change, the cached hash would become wrong, and a key could become lost inside a map, stored in one bucket while its hash now points to another.

4Benefit 3: Security of Checked Values

A lot of security checks take a String, check it, and then use it. A file path is checked against an allowed directory, then opened. A class name is checked against an allow-list, then loaded. A host name is checked, then connected to. If the String could change between the check and the use, an attacker in another thread could pass the check with a safe value and then change it to a dangerous one. This is called a time-of-check to time-of-use problem.

Java
void openReport(String path) {
if (!path.startsWith("/reports/")) throw new SecurityException("not allowed");
// if String were mutable, another thread could change path here
Files.readString(Path.of(path)); // safe: path is exactly what we checked
}

Because String is immutable, the value we checked is guaranteed to be the value we use. This is one of the original reasons the JDK designers gave for immutability, since the class loader, file APIs and network APIs all take String parameters.

5Benefit 4: The String Pool

Java keeps a pool of string literals, so every occurrence of the literal "OK" in a program refers to the same String object. intern() adds a string to the pool or returns the pooled copy. This sharing saves memory and makes literal comparisons cheap, but it is only possible because pooled strings can never change. If one part of the program could modify the pooled "OK", every other part using the literal would see the change.

Java
String a = "OK";
String b = "OK";
System.out.println(a == b); // true: the same pooled object
String c = new String("OK");
System.out.println(a == c); // false: a separate object
System.out.println(a == c.intern()); // true: intern() returns the pooled one
Benefits of immutability and what they rely on
BenefitWhat it enablesWhy immutability is required
Safe sharingno copies, no locksno caller or thread can change the value
Cached hash codecheap String keys in HashMapthe hash can never become stale
Checked values stay checkedsafe paths, class names, URLsvalue at use equals value at check
String poolshared literals, less memoryone change would affect every user
Cost: new object per changeuse StringBuilder in loopsthe original can never be edited

6The Cost: Every Change Is a New Object

The price is paid when we build or edit text step by step. Each concatenation in a loop creates a new String and copies all the characters so far, so building a string of n pieces this way does work proportional to n squared. For a few pieces it does not matter, and javac already compiles a single expression like a + b + c efficiently. In a loop it matters a lot, and StringBuilder, a mutable buffer of characters, is the answer.

Java
String slow = "";
for (int i = 0; i < 10_000; i++) slow += i; // 10,000 new Strings, each copying the last
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10_000; i++) sb.append(i); // appends into one growing buffer
String fast = sb.toString();
System.out.println(slow.equals(fast)); // true

A second, smaller cost: a password held in a String cannot be wiped from memory after use, because we cannot overwrite its characters, so security-sensitive APIs such as the console's readPassword use a char array that can be cleared.

7Follow-up questions

Is String final only to stop subclassing, or does that matter for immutability too?

It matters for immutability. If String could be subclassed, someone could write a subclass that overrides methods or adds mutable state, and pass it wherever a String is expected. Code that relies on Strings never changing, such as HashMap, the security checks or the pool, could then be fooled. Making the class final guarantees that every String really is the JDK's immutable implementation.

Is String immutable even through reflection?

Ordinary code cannot change it. Since Java 17 the module system strongly encapsulates java.base, so setAccessible on String's internal fields fails unless the package is explicitly opened with --add-opens, which is one more layer protecting the guarantee.

Should my own value classes be immutable too?

Usually yes, for the same reasons: safe sharing, safe use as map keys and simpler reasoning. Records make this easy, because their fields are final, although a record holding a mutable List still needs a defensive copy such as List.copyOf in its constructor.

8Conclusion

In this answer, we saw that String is immutable because its characters can never change after construction. That lets the same instance be shared across threads and callers without copies or locks, lets String cache its hash code for cheap map lookups, keeps checked paths and class names safe between check and use, and makes the string pool possible. The cost is a new object for every change, which is why repeated edits belong in a StringBuilder, and we saw that making the class final is part of what guarantees the immutability.

What to say in the interviewAbout 80 seconds aloud

Open with

String is immutable so a String value can be trusted wherever it goes, and that gives several concrete benefits. First, safe sharing: many threads and callers can use the same instance without locks, and a class can store a String it was given without a defensive copy, unlike a List.

Then, if they want more

Second, String can cache its hash code in a field, because the characters never change, so after the first call hashing is free, which is why String keys are cheap in a HashMap, and why a key can never get lost by changing after insertion.

Third, security: a file path, class name or URL that was checked cannot be changed by another thread before it is used, so there is no time-of-check to time-of-use gap. Fourth, the string pool: literals can be shared across the whole program only because nobody can modify them.

The cost is that every change creates a new object, so concatenating in a loop is quadratic, and I use StringBuilder for that. A smaller cost is that passwords in a String cannot be wiped, so we use a char array.

And the class being final matters too: without it, a mutable subclass could be passed anywhere a String is expected.

About this answer

Last updated
12 November 2026
Versions it names
Java 17, Java 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why is String immutable in Java? Give at least four concrete benefits and one cost.": https://scrivio-interview-library.netlify.app/java/strings/5a87415db5/

More in Strings and text