What is the String pool, and how does String immutability relate to it?
Quick Answer
The String pool (a special area of the heap) caches String literals so identical literals are reused instead of duplicated. This works because String is immutable — a shared instance can never be mutated out from under another reference. String.intern() manually adds/looks up a string in the pool.
Detailed Answer
String is immutable — once created, its character content can never change; every "modifying" operation (concat, substring, replace, ...) returns a new String.
Because strings can't be mutated, the JVM can safely let many references share the same underlying String object. The string pool (part of the heap since Java 7) is a table of unique string instances. String literals are automatically interned:
String a = "hello";
String b = "hello";
a == b; // true — both point at the same pooled instance
String c = new String("hello"); // forces a new, non-pooled object
a == c; // false
c.intern() == a; // true — intern() looks up/adds to the pool
Benefits: memory savings (one copy of a repeated literal) and fast reference comparisons for pooled strings.
Why immutability enables this: if String were mutable, sharing instances would be dangerous — modifying one reference would silently corrupt every other reference to the "same" string. Immutability is also why String is safe as a HashMap key (its hash code is cached after first computation) and safe to share across threads without synchronization.