Java Reference ยท java.lang
Java String.intern() and the string pool
Reference for Java String.intern() and the string pool: why literals share objects, how == behaves, and why equals() is still the right comparison.
The JVM keeps a pool of unique strings. Every string literal in your code, and every compile-time constant expression, refers to the one pooled instance for that text. Two identical literals are therefore the very same object, which is why "hi" == "hi" is true.
intern() lets you ask the pool explicitly: it returns the pooled instance with the same contents, adding the string to the pool first if needed. Strings created at run time (with new String(...), concatenating variables, reading input) are not pooled until you intern them.
String a = new String("java"); String b = a.intern(); System.out.println(b == "java"); // true
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public String intern()
Returns: a string with the same contents as this one that is guaranteed to come from the pool. For any two strings s and t, s.intern() == t.intern() is true exactly when s.equals(t) is true.
Throws: nothing.
Usage notes
- Never use
==to compare strings in application code, even if it happens to work today. Useequals(). Reference equality is an implementation detail that breaks as soon as a value comes from input, a file or a concatenation. - Where the pool lives. Since Java 7 the pool is part of the ordinary heap, so interned strings can be garbage collected when nothing refers to them. In Java 6 and earlier it lived in the permanent generation and could overflow.
- Pool lookups are not free.
intern()is a native call into a hash table. Interning millions of distinct values is slow and rarely worth it. - Legitimate uses are narrow: saving memory for huge numbers of repeated strings you hold for a long time, or enabling identity comparison inside a tightly controlled parser or compiler. For the memory goal, the G1 option
-XX:+UseStringDeduplicationdoes it without code changes. switchon strings usesequals()/hashCode(), not identity, so it works for runtime strings too.- Enums and constants are better than interned strings as identifiers when the set of values is fixed.
- Text blocks and literals concatenated with
+at compile time also land in the pool.