Sub topic 1
Why Strings Are Immutable
A Java String never changes after it is created. Every method that looks like an edit hands back a new object and leaves the original alone. This chapter explains the working model behind that rule, why the language designers chose it, and the mistakes it causes in everyday code. Later chapters build on it: it is the reason repeated concatenation is costly, and the reason StringBuilder exists.
Prerequisites
This chapter assumes you can do the following:
- Write and run a small Java program with
main, variables, loops, and methods. - Use
Stringand the+operator. - Tell objects from primitives, and know that a variable of object type holds a reference.
- Compile with a recent JDK. Everything in this chapter runs on JDK 17 or later.
What "Immutable" Means
An immutable object is one whose state cannot change after construction. For a String, the state is the sequence of characters. No method on String can add, remove, or replace a character in an existing instance.
Methods such as toUpperCase, replace, trim, substring, and concat return a new String. They never modify the receiver.
public class ImmutableDemo {
public static void main(String[] args) {
String name = "ada";
String upper = name.toUpperCase();
System.out.println(name); // ada
System.out.println(upper); // ADA
name.concat(" lovelace"); // result is discarded
System.out.println(name); // ada
name = name.concat(" lovelace");
System.out.println(name); // ada lovelace
}
}The call name.concat(" lovelace") on its own line does nothing useful. It builds a new string, and the program throws it away. Only the assignment on the last step changes what name refers to.
Variables Are References, Not Strings
A String variable does not contain the characters. It holds a reference to a String object on the heap. Immutability applies to the object. The variable can point somewhere else at any time.
public class AliasDemo {
public static void main(String[] args) {
String a = "java";
String b = a; // b refers to the same object as a
a = a + "!"; // a now refers to a new object
System.out.println(a); // java!
System.out.println(b); // java
}
}Because the object cannot change, the assignment b = a is safe. Nothing done through a can alter what b sees. With a mutable type, aliasing like this is a common source of bugs.
final Is Not the Same Thing
Two different ideas are easy to confuse:
- A
finalvariable can be assigned only once. It restricts the reference. - An immutable object cannot change its contents. It restricts the object.
final String s = "x"; gives you both, but only because String is immutable. A final StringBuilder sb can still be appended to freely. The final stops you from pointing sb at another builder, not from changing the builder.
How the Class Enforces It
Immutability in String comes from how the class is built, not from a special compiler rule. In OpenJDK the class has these properties:
Stringis declaredfinal, so no subclass can add mutable state or override methods to behave differently.- The characters live in a
private finalarray (abyte[]in JDK 9 and later), and no method exposes that array. - No method writes to the array after the constructor finishes.
- Methods that return character data, such as
toCharArray, return a copy. Changing the copy does not affect the string.
public class CopyDemo {
public static void main(String[] args) {
String s = "hello";
char[] chars = s.toCharArray();
chars[0] = 'J';
System.out.println(new String(chars)); // Jello
System.out.println(s); // hello
}
}The array is a copy, so editing chars is the closest thing Java gives you to editing a string. You then build a second string from the edited array.
Reflection Does Not Change the Contract
Older code sometimes used reflection to write into a string's internal array. This is not a supported technique. Since JDK 16 the module system denies deep reflection into java.lang by default, and JDK 17 removed the command-line switch that allowed it. Treat strings as immutable without exception.
Why the Designers Chose Immutability
The design has several consequences, each of which matters in real programs.
Safe Sharing and String Reuse
The JVM keeps a pool of string objects for literals. Two literals with the same text can be the same object, because nobody can modify the shared instance. This saves memory in programs that repeat text such as keys, column names, and log messages. It only works because sharing is safe.
Thread Safety Without Locks
An object whose state never changes can be read from many threads with no synchronization. Any thread holding a String sees the same characters as every other thread. You never need to copy a string defensively before handing it to another thread.
Cached Hash Codes and Reliable Map Keys
String computes its hash code once and stores it in a field. Because the characters cannot change, the cached value stays correct. Strings are used as HashMap keys constantly, so this makes lookups cheaper.
Immutability also protects map keys. A HashMap places a key in a bucket based on its hash at insertion time. If the key later changes, the entry is stranded. The example below uses a mutable List as the key to show the failure:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MutableKeyDemo {
public static void main(String[] args) {
List<String> key = new ArrayList<>(List.of("a"));
Map<List<String>, String> map = new HashMap<>();
map.put(key, "value");
key.add("b"); // the key's hash code and equality both change
System.out.println(map.get(key)); // null
System.out.println(map.containsKey(List.of("a"))); // false
System.out.println(map.size()); // 1
}
}The entry is still in the map, but it cannot be found with the changed key. It cannot be found with the original value either, because the stored key no longer equals List.of("a"). A String key can never end up in this state.
Security Checks That Stay Valid
Code often validates a value and then uses it: a file path, a class name, a URL, a user name. If the value were mutable, another thread or a caller holding the same reference could change it between the check and the use. With strings, the checked value is the used value. The JDK relies on this in class loading, file access, and network code.
The Trade-off
Immutability has a cost. Every change creates a new object, so code that makes many small edits to one piece of text does extra allocation and copying. The next chapter measures that cost, and the chapter after it introduces StringBuilder as the mutable alternative.
Identity Versus Equality
Immutability and the string pool explain a classic surprise: == and equals can give different answers.
==compares references: are these the same object?equalscompares contents: do these hold the same characters?
public class IdentityDemo {
public static void main(String[] args) {
String x = "hello";
String y = "hello";
String z = new String("hello");
String w = z.intern();
System.out.println(x == y); // true (same pooled literal)
System.out.println(x == z); // false (new object on the heap)
System.out.println(x.equals(z)); // true (same characters)
System.out.println(x == w); // true (intern returns the pooled one)
}
}new String("hello") always creates a fresh object. intern() returns the pooled instance with the same contents, adding it to the pool if needed.
Compile-Time Constants Versus Runtime Concatenation
The compiler folds concatenations of constants into one literal. Concatenation involving non-constant values happens at run time and produces a new object.
public class ConstantFoldingDemo {
public static void main(String[] args) {
String x = "hello";
final String part = "hel";
String c = part + "lo"; // constant expression, folded to "hello"
String part2 = "hel";
String d = part2 + "lo"; // computed at run time
System.out.println(x == c); // true
System.out.println(x == d); // false
System.out.println(x.equals(d)); // true
}
}The only difference between part and part2 is the final modifier. A final variable initialized with a constant counts as a constant, so the compiler can fold it.
Common Errors
Ignoring the Return Value
This is the most frequent immutability bug. The following line compiles and runs and does nothing:
String title = " Report ";
title.trim(); // result discarded, title is unchanged
title = title.trim(); // correctStatic analysis tools and IDEs usually flag a discarded result from a String method. Treat that warning as an error.
Expecting a Method to Change All Aliases
Because String methods return new objects, a method that receives a string cannot modify the caller's variable:
public class PassByValueDemo {
static void shout(String s) {
s = s.toUpperCase(); // only changes the local parameter
}
public static void main(String[] args) {
String word = "quiet";
shout(word);
System.out.println(word); // quiet
}
}A method that wants to give back a changed string must return it.
Assuming a New Object Every Time
Some methods return the receiver itself when no change is needed. For example, trim on a string with no surrounding whitespace, or toUpperCase on a string that is already upper case, commonly returns the same instance. This is an implementation detail and can differ between JDK versions. Never rely on == to detect whether a method "did something". Use equals.
Secrets in Strings
A password held in a String stays in memory until the garbage collector reclaims it and the memory is overwritten, and you cannot wipe it yourself. A char[] can be overwritten when you are done with it. This is why java.io.Console.readPassword returns char[] and why many security APIs accept arrays.
char[] password = {'s', '3', 'c', 'r', 'e', 't'};
// ... authenticate ...
java.util.Arrays.fill(password, '\0'); // wipe the contentsThis does not make code safe by itself, since copies may already exist elsewhere, but it reduces how long the secret stays readable.
Substring Memory Concerns
In very old JDKs (before 7u6), substring shared the parent's character array, so a tiny substring could keep a huge string alive. Modern JDKs copy the characters. Advice you may find online about "substring memory leaks" is out of date for current Java.
Summary Table
| Operation | Changes the original? | Returns |
|---|---|---|
| `s.toUpperCase()` | No | New or same `String` |
| `s.replace('a', 'b')` | No | New or same `String` |
| `s.substring(1, 3)` | No | New `String` |
| `s.toCharArray()` | No | A copy as `char[]` |
| `s = s + "x"` | No, but `s` now refers to a new object | Assignment result |
| `final String s` reassigned | Compile error | Not applicable |
Exercise
What does this program print, and why? String a = "cat"; String b = a; a.concat("s"); b = b.toUpperCase(); System.out.println(a + " " + b);
Show answer
It prints "cat CAT". The call a.concat("s") returns a new string that is discarded, so a still refers to "cat". The call b.toUpperCase() returns a new string "CAT", which is assigned to b. That assignment moves the reference b and leaves the object "cat" untouched, which a still refers to.
Exercise
Given String p = "ab"; String q = "a" + "b"; String r = "a"; String s = r + "b";, which of p == q, p == s, and p.equals(s) are true?
Show answer
p == q is true, because "a" + "b" is a constant expression that the compiler folds into the pooled literal "ab". p == s is false, because r is not final, so r + "b" is computed at run time and produces a new object. p.equals(s) is true, because the characters are the same.
Exercise
A teammate declares final StringBuilder sb = new StringBuilder("x"); and says the final keyword makes sb immutable. Is that right?
Show answer
No. final only prevents reassigning the variable sb to another object. The StringBuilder it refers to is mutable, so sb.append("y") is allowed. A String is immutable because of how the class is built (a final class with private, never-modified internal data), not because of any final on a variable.