What is String Pool in Java?
sobes.tech AI
Answer from AI
String Pool (also known as String Intern Pool) is a special memory area in Java's heap (Heap) where the JVM stores string literals (String literals).
When creating a string literal, for example String s = "Hello";, the JVM first checks if a string with the same value already exists in the String Pool.
- If the string already exists, the variable
swill point to the existing object in the String Pool. - If the string does not exist, a new string object is created in the String Pool, and the variable
spoints to this new object.
This is an optimization that saves memory by reusing identical string values.
Creating a string using the new String() operator always creates a new object in the heap, regardless of whether such a string exists in the String Pool.
// Refers to an object in the String Pool
String s1 = "Hello";
// Refers to an object in the String Pool (the same as s1)
String s2 = "Hello";
// Creates a new object in the heap, not in the String Pool
String s3 = new String("Hello");
// Refers to an object in the String Pool if it is not already there.
// If it exists, returns a reference to the existing object.
String s4 = s3.intern();
s1 == s2will betrue.s1 == s3will befalse.s1 == s4will betrue.
The intern() method allows explicitly placing a string into the String Pool or obtaining a reference to it if it is already there.
Before Java 7, the String Pool was located in PermGen (a memory area for class metadata), but starting from Java 7, it is in the Heap.