library
advancedString Pool & String Internment
Understand how Java optimizes String storage with the string pool and when intern() matters.
Java maintains a String Pool (also called intern pool) in the heap (moved from PermGen to heap in Java 7). String literals are automatically interned — identical literals share the same object reference.
String pool = a library's card catalog. When you write a book title (literal), the library checks if it already has a card. If yes, you get the existing card (same reference). If you photocopy the title (new String), you get your own card — unless you ask the library to file it (intern()).
Key Concepts
1
String pool behavior:
- "hello" and "hello" → same reference (== returns true)
- new String("hello") → creates a new object on heap, NOT in the pool
- new String("hello").intern() → returns the pooled reference
2
String.intern(): checks if an equal string exists in the pool. If yes, returns the pool reference. If no, adds this string to the pool and returns it. After intern(), == comparison works.
3
When intern() helps:
- Processing millions of strings with many duplicates (XML tags, column names, country codes)
- Reducing memory when the same strings appear repeatedly
- Enabling fast == comparison instead of equals()
4
When intern() hurts:
- Unique strings: every string added to the pool stays there (until GC)
- Pool lookup has overhead — don't intern strings compared only once
- Before Java 7, interned strings lived in PermGen (fixed size) → OutOfMemoryError
5
Since Java 9, String uses compact storage: Latin-1 strings use byte[] (1 byte/char) instead of char[] (2 bytes/char). This halves memory for ASCII-only strings.