Junior
What is a string pool in Java?
sobes.tech AI
Answer from AI
String pool is a special area in the heap where the JVM (Java Virtual Machine) stores string literals (String literals).
When a string literal is created, the JVM first checks the string pool for an identical string.
- If the string is found, a reference to the existing object in the pool is returned.
- If the string is not found, a new
Stringobject is created inside the string pool, and a reference to it is returned.
This is an optimization to save memory, as multiple string literals with the same content can share the same String object in the pool.
Example:
// Creates a string literal, "hello" is added to the string pool if not already present
String s1 = "hello";
// Creates a string literal, "hello" already exists in the pool, returns a reference to the existing object
String s2 = "hello";
// s1 and s2 refer to the same object in the string pool
System.out.println(s1 == s2); // true
// Creates a new String object on the heap outside the string pool
String s3 = new String("hello");
// s1 and s3 refer to different objects
System.out.println(s1 == s3); // false
// The intern() method "interns" the string, adding it to the string pool
// If "hello" already exists in the pool, a reference to the object in the pool is returned
String s4 = s3.intern();
// s1 and s4 refer to the same object in the string pool
System.out.println(s1 == s4); // true
The string pool is managed by the JVM and is part of the Young Generation. It improves performance by reducing the number of String objects created.