Card 04/ 09

ConceptDifficulty: Beginner1 min

Two Ways to Make the Same Text, and Why One Is Shared

A large program has the word "ACTIVE" written in forty places. Storing forty copies of six characters would be wasteful, and the JVM does not.

Every string literal — text in double quotes in your source — is put in a shared table called the string pool. The first time the JVM meets "ACTIVE" it creates one object and puts it in the pool. Every later occurrence of the same literal gets the address of that one object.

java
String a = "ACTIVE";
String b = "ACTIVE";
String c = new String("ACTIVE");
Two literals share one pooled object; new String makes a second one

new String(...) is the one way to opt out. The keyword new is a demand for a fresh object, so it makes a second one holding identical characters, and that second one is not in the pool.

Sharing is only safe because strings cannot be changed. If one of those forty places could alter the pooled object, the other thirty-nine would see it — so immutability is what pays for the pool, rather than the other way round.