Card 04/ 09
The String Pool: Why Identical Literals Are Shared
"ACTIVE" written in forty places, and one object in memory.
Java keeps one shared copy of each distinct string literal, text written in double quotes in your source, in a table called the string pool. Every use of the same literal refers to that one object. new String(...) opts out and always creates a separate object.
A large program has the word "ACTIVE" written in forty places. Storing forty copies of six characters would be wasteful, and the JVM, the Java Virtual Machine that runs your program, does not. The first time it 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.
String a = "ACTIVE";
String b = "ACTIVE";
String c = new String("ACTIVE");a and b hold the same address, so a == b is true, while a == c is false even though all three hold the same six characters. 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.
Strings built while the program runs, from a file, from user input, or by joining strings held in variables, are not pooled either. Only the literals in your source are shared automatically.
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.
← → move through sections and cards