Java String Pool / String literal pool / String interning
The string pool is the JVM’s particular implementation of the concept of string interning:
In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.
Basically, a string intern pool allows a runtime to save memory by preserving immutable strings in a pool so that areas of the application can reuse instances of common strings instead of creating multiple instances of it.
As an interesting side note, string interning is an example of the flyweight design pattern.
The JVM String Pool is a mechanism to optimize memory usage and potentially improve performance by reusing immutable String objects.
The JVM (Java Virtual Machine) String Pool is a special memory area within the Java heap where the JVM stores String literals. It is also known as the String Constant Pool or String Intern Pool.
Here’s how it works:
- String literals are stored in the pool: When you create a String literal (e.g., String str = “hello”;), the JVM first checks if a String with the same value already exists in the pool.
- Reusing existing Strings: If the String already exists, the JVM returns a reference to the existing String object in the pool, instead of creating a new one.
- Creating new Strings: If the String doesn’t exist in the pool, the JVM creates a new String object in the pool and returns a reference to it.
- Immutability enables pooling: String objects are immutable in Java, meaning their values cannot be changed after they are created. This immutability allows the JVM to safely reuse String objects from the pool without worrying about unintended modifications.
Benefits of the String Pool:
- Memory efficiency: By reusing existing String objects, the String Pool reduces memory consumption and the number of String objects created.
- Performance improvement: Comparing String references (using ==) is faster than comparing String values (using .equals()). Since pooled Strings can be compared by reference, this can lead to performance gains.
String Creation with new Keyword:
- When you create a String object using the new keyword (e.g., String str = new String(“hello”);), a new String object is created in the heap, regardless of whether a String with the same value already exists in the pool.
- To add a String created with new to the pool, you can use the intern() method: String str = new String(“hello”).intern();.
See