All topics
library
beginner

String Immutability & String Pool

Understand why Strings are immutable, how the String Pool works, and the performance implications.

Strings in Java are immutable: once created, their content never changes. Every method that appears to modify a String (concat, replace, toUpperCase) returns a new String object.

String Pool = a library's reference shelf. Instead of buying the same book twice, the library keeps one copy and gives everyone the same reference.

Key Concepts

1
Why immutable? 1. Thread safety: immutable objects are inherently thread-safe — no synchronization needed. 2. Security: Strings are used for class loading, network connections, file paths. Mutable strings would be a security risk. 3. Hash code caching: String caches its hashCode after first computation. This makes String keys in HashMap very fast. 4. String Pool: the JVM can safely share identical String instances because they can't be modified.
2
The String Pool (String Intern Pool) is a special memory area where the JVM stores unique string literals. When you write "hello", the JVM checks the pool — if "hello" already exists, it reuses the same object. This saves memory when the same string appears many times.
"hello"
3
new String("hello") creates a new object on the heap, bypassing the pool. str.intern() adds the string to the pool (or returns the existing pooled instance).
new String("hello")str.intern()
4
Since Java 9, String uses a compact byte[] representation: Latin-1 strings use one byte per character, UTF-16 strings use two bytes. This reduces memory for ASCII-heavy workloads by ~50%.