String pool
The string pool is a JVM table of unique String instances. Literals and interned strings go there so equal character sequences can share one object.
Detailed Explanation
"hello" in source code is stored in the class file and resolved to a pooled String. Two literals with the same characters in the same or different classes usually compare == true because they are the same object. new String("hello") allocates a distinct object whose contents happen to match. equals is true; == is false.
String.intern() looks up the pool and returns the pooled instance, inserting this string if needed. Interning a huge unique string keeps it alive as long as the pool holds it (the pool is a GC root for those entries in the intern table, with details that changed when the pool moved to the heap in Java 7). Interning every request payload is a leak.
The pool exists because strings are immutable and common. Class names, identifiers, and many map keys repeat. Sharing them saves memory and makes == a fast path the JDK sometimes uses internally after intern. Your code should still use equals.
You reach for intern only when you have a small, closed set of repeated values and a measured memory win (canonicalizing enum-like tokens). You do not intern user input. You do not intern every JSON field name unless a profiler said so.
The cost of the pool is a table and the lifetime of interned strings. The cost of relying on == for literals is a bug the first time the same text arrives from a file. The cost of new String(literal) is a wasted copy; linters flag it.
Compact strings (Java 9+) store Latin-1 in bytes; that is orthogonal to pooling. Pooled strings still use that encoding.
Code Examples
public class Literals {
public static void main(String[] args) {
String a = "token";
String b = "token";
String c = new String("token");
System.out.println(a == b); // prints: true
System.out.println(a == c); // prints: false
System.out.println(a == c.intern()); // prints: true
}
}public class Built {
public static void main(String[] args) {
String built = "to" + "ken"; // compile-time constant, still pooled
String runtime = "to".concat("ken");
System.out.println(built == "token"); // prints: true
System.out.println(runtime == "token"); // prints: false
}
}Common Gotchas
`==` on runtime strings is almost always wrong
use `equals`.
Interning unbounded user data fills the heap
the intern table retains the strings.
`new String("x")` is a second object
never write it to "get a string".
Compile-time constant concatenation is pooled; `concat` at runtime is not
Compile-time constant concatenation is pooled; `concat` at runtime is not