Junior
What is the purpose of String Pool in Java?
sobes.tech AI
Answer from AI
String Pool in Java is necessary for:
- Memory saving: Prevents creating duplicate string literals. If a string with the same value already exists in the pool, a reference to it is used.
- Performance optimization: Comparing string literals (
==) becomes faster because references are compared, not the content of the strings.
When creating string literals (String s = "hello";), the JVM first checks the String Pool. If "hello" already exists, s references the existing object. If not, a new "hello" object is created in the pool, and s references it.
Using the constructor new String("hello") always creates a new String object in the heap, regardless of the String Pool. To add it to the pool, the intern() method must be called.
// Example of String Pool operation
String s1 = "hello"; // Checks String Pool, creates if necessary, references the pool
String s2 = "hello"; // Checks String Pool, finds existing, also references the pool
System.out.println(s1 == s2); // true - references are the same
String s3 = new String("hello"); // Creates a new object in the heap
System.out.println(s1 == s3); // false - references are different
String s4 = s3.intern(); // Checks String Pool for s3's content.
// Since "hello" already exists in the pool (from s1/s2),
// s4 references the object in the pool.
System.out.println(s1 == s4); // true - s1 and s4 reference the same object in the pool