What does String.intern() do?

6 minintermediateinternstring-poolstring

Quick Answer

String.intern() looks up the string pool for a string with the same content as the current string; if found, it returns that pooled reference, otherwise it adds the current string's content to the pool and returns a reference to it. This lets you force any dynamically-created String (e.g., from new String(...) or concatenation) to be deduplicated against the pool, enabling == comparisons and memory savings for strings you know are frequently repeated.

Detailed Answer

String.intern() explicitly ties a String instance to the JVM's string pool (the same pool that string literals are automatically placed in):

String a = new String("hello"); // NOT in the pool — a fresh heap object
String b = "hello";              // literal — automatically in the pool

a == b;              // false — different objects
a.intern() == b;     // true — intern() finds/returns the pooled "hello"

Behavior: intern() checks whether a string with the same content already exists in the pool. If so, it returns that existing pooled reference (discarding the caller's distinct instance, from a reference-identity perspective); if not, it adds the current string to the pool and returns a reference to it.

Why use it: if you know a specific string value recurs very frequently (e.g., parsed tokens, repeated field values from a large dataset), interning lets multiple otherwise-independent String objects collapse into one shared instance — saving memory, and enabling fast == comparisons where content equality is guaranteed by the fact that both references point at the same pooled object.

Caveat: interning has a cost (a pool lookup, and potentially growing the pool), so indiscriminately interning every string can increase memory pressure and hurt performance rather than help — it's a targeted optimization for specific, measured cases of highly repeated string values, not a general-purpose habit.