Scrivio Interview library
ConceptPrincipal7 min read · updated 12 November 2026

String has been final and immutable since Java 1.0. Explain why that early decision still shapes security, performance and API design in the platform, and what lesson it offers for designing core types in your own organization.

Because String is immutable, every part of the platform can trust a String it receives: a class name, file path or host checked once stays the same when it is used, its hash code can be cached, and literals can be shared across the whole JVM. Because it is also final, no subclass depends on its internals, which let the JDK change its storage from char[] to byte[] with a coder in JDK 9 without breaking anyone. The lesson is that widely shared core types should be immutable and closed to subclassing so their implementation can evolve, at the cost of needing separate types for mutable work.

Why this question is asked

At the twenty-year level this question is less about String and more about design judgement. String is the most shared type in Java: almost every API takes one, and decisions made about it in 1995 still decide what the JDK can and cannot do. Interviewers want to see that we can connect a language-level decision to security, performance and evolution, and turn it into guidance for our own shared libraries. In this answer, we will recap what final and immutable mean for String, look at what immutability buys in security and in performance, see how being final allowed the JDK to change String's insides, and then draw the lesson for designing our own core types, including what it costs.

1A Quick Recap: Final and Immutable Are Two Different Promises

Immutable means a String's value never changes after construction. Every method that seems to modify it, such as toUpperCase or replace, returns a new String. Final means nobody can write class MyString extends String. The two promises support each other: if subclassing were allowed, a subclass could add a mutable field or override length() and charAt(), and code that received a String could no longer trust it to behave like one.

So when a method's parameter type is String, the method knows the exact class of the object it gets, and it knows the value cannot change while it works with it. Almost every argument for String's design follows from that single guarantee.

2What Immutability Buys in Security

Large parts of the platform take names as strings: Class.forName and ClassLoader.loadClass take class names, FileInputStream and Path.of take paths, sockets take host names, and reflection looks up methods by name. Many of these do a check first and the actual work afterwards. If the String could change between the two steps, an attacker could pass a harmless value, let the check approve it, and then change it before the operation runs. This is called a time-of-check to time-of-use attack.

Java
// What a check-then-use API looks like
void open(String path) {
if (!allowed(path)) throw new SecurityException(path); // check
// ... if another thread could now change path to "/etc/shadow" ...
nativeOpen(path); // use
}

With an immutable, final String, the value checked is the value used, without the API having to make a defensive copy. The Security Manager that relied on this most heavily has since been deprecated (JEP 411, Java 17) and permanently disabled in JDK 24, but the same reasoning applies to class loading, module checks, caches keyed by name and any code of ours that validates input and then acts on it.

3What Immutability Buys in Performance

Three well-known optimisations exist only because a String's content never changes. The first is hash caching: String computes its hash code on the first call to hashCode() and stores it in a field, so a String used as a HashMap key is hashed once, not on every lookup. If the content could change, the cached hash would be wrong and the entry would be lost in the map.

The second is pooling. Every string literal with the same content is one shared object for the whole JVM, and intern() extends that to runtime strings. Sharing is only safe because nobody can change the shared value. The third is that the collectors' string deduplication can make two equal Strings share one backing array, and compact strings can choose a one-byte-per-character layout once at construction. Both depend on the content being fixed.

Platform features that depend on String's design
FeatureSinceRelies on
Hash code cached in the objectJDK 1.0immutable content
Shared literals and intern()JDK 1.0immutable content
substring copies, no offset/countJDK 7u6final: no subclass used those fields
Compact strings: byte[] plus coderJDK 9final and immutable
String deduplication in the GCJDK 8u20 (G1)immutable content, identity unchanged
Concatenation via invokedynamicJDK 9String's exact class is known
Each change helped every program without code changes because no caller or subclass could depend on the old layout.

4How Being Final Let the JDK Change String's Insides

For nearly twenty years a String stored its characters in a char[], two bytes per character. In JDK 9, compact strings (JEP 254) changed that to a byte[] plus a coder field that says whether the bytes are Latin-1, one byte per character, or UTF-16, two bytes per character. For typical text this halved the memory used by strings, and every Java program got that benefit by upgrading.

That change was possible because String is final and its fields are private. If subclasses had existed, some of them would have read the value field, overridden charAt() assuming a char[] behind it, or serialized the layout, and the JDK would have been stuck. The same freedom allowed the 7u6 removal of offset and count. A final class with private state has one implementation, owned by its authors, and they can rewrite it as long as the public methods keep their contract.

5The Lesson for Our Own Core Types

Every organization has its own String-like types: a CustomerId, a Money amount, a TenantId, an Address, a shared Event envelope. They appear in hundreds of services, so the cost of changing them later is enormous. The String story suggests three rules. Make them immutable, so they can be shared, cached and used as map keys safely. Make them final or sealed, or simply use records, which are final and shallowly immutable, so nobody depends on an internal detail through a subclass. And hide the representation behind methods and factories, so we can change storage later without touching callers.

Java
public record Money(long minorUnits, Currency currency) { // final, immutable fields
public Money {
Objects.requireNonNull(currency);
}
public static Money of(String amount, String code) { // factory hides the representation
Currency c = Currency.getInstance(code);
return new Money(new BigDecimal(amount).movePointRight(c.getDefaultFractionDigits()).longValueExact(), c);
}
public Money plus(Money other) { // returns a new value, like String.concat
if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
return new Money(Math.addExact(minorUnits, other.minorUnits), currency);
}
}
Money price = Money.of("19.99", "EUR");
System.out.println(price.plus(price).minorUnits()); // 3998

Callers only see the factory and the operations, so we can later change the internals, exactly as the JDK did with String's array.

6What the Decision Costs

Immutability is not free. Every modification creates a new object, so building text piece by piece needs a separate mutable type, which is why Java has StringBuilder, StringBuffer and CharBuffer. A naive loop that uses += on a String copies everything on each iteration. We also cannot add behaviour by subclassing, which is why every codebase has a StringUtils class full of static helpers.

Our own types pay the same price: an immutable Order needs a builder or with-methods, so we should ship that mutable companion from the start.

7Follow-up questions

Why not make String an interface with several implementations?

Because then no method receiving a String could trust it. Any implementation could be mutable or have a different equals(), and the JVM could not pool, cache hashes or intrinsify operations on a single known layout. CharSequence plays the role of the open interface, and String is the closed, trusted implementation.

Does a record give us everything String has?

Records are final and their fields are final, but they are only shallowly immutable. A record holding a List or an array can still be changed through that component, so we copy collections in the compact constructor with List.copyOf and avoid exposing arrays. Records also expose their components publicly, so they suit values whose representation is the API, while a final class with private fields suits types whose storage may change.

8Conclusion

In this answer, we saw that String's two promises, immutable content and a final class, let the platform trust names and paths passed to class loading, file and security code, let it cache hash codes, pool literals and deduplicate arrays, and let the JDK rewrite String's storage in 7u6 and again in JDK 9 without breaking anyone. The lesson for our own organization is that widely shared core types should be immutable, closed to subclassing and should hide their representation, and that we should ship a mutable builder alongside them because modifying immutable values costs new objects.

What to say in the interviewAbout 90 seconds aloud

Open with

I would say the decision paid off in three ways. For security, half the platform takes Strings as names: class names, file paths, host names, reflection. Those APIs check a value and then use it, and because String is immutable and final, the value checked is guaranteed to be the value used, without defensive copies.

Then, if they want more

For performance, String caches its hash code, literals are shared across the whole JVM, and the collectors can deduplicate backing arrays, and all of that is only safe because content never changes.

And for evolution, because String is final with private fields, no subclass ever depended on its layout, so the JDK could drop the offset and count fields in 7u6 and switch from char arrays to byte arrays with a coder in JDK 9. Every application got a big memory saving just by upgrading.

The lesson I take for an organization is to treat our own shared core types the same way. Things like CustomerId, Money or an event envelope should be immutable, final or records, and hide their representation behind factories and methods, so the platform team can change the storage later without a coordinated migration across a hundred services.

The cost is that changes create new objects and people need a mutable companion, like StringBuilder for String, so I would ship a builder with each type from day one rather than let teams work around it.

About this answer

Last updated
12 November 2026
Versions it names
Java 9, Java 17, Java 24
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 "String has been final and immutable since Java 1.0. Explain why that early decision...": https://scrivio-interview-library.netlify.app/java/strings/9895d044f2/