Junior
What is a string pool in Java?
sobes.tech AI
Answer from AI
String pool — is a special area of memory in the Java heap where string literals and interned strings are stored. Its main purpose is to save memory by reusing identical string values.
How it works:
When a string literal is created (for example, "hello"), the JVM first checks if a string with the same value already exists in the string pool.
- If the string exists: JVM returns a reference to the existing object in the pool instead of creating a new one.
- If the string does not exist: JVM creates a new
Stringobject in the string pool and returns a reference to it.
Creating strings and the pool:
- Using a string literal:
// "hello" is a string literal String s1 = "hello"; String s2 = "hello"; // s1 and s2 will refer to the same object in the string pool - Using the
new String()constructor:String s3 = new String("world"); String s4 = new String("world"); // s3 and s4 will refer to different objects in the heap, even if their values are the same. // The string literal "world" may be in the pool, but s3 and s4 objects are outside it. - The
intern()method:String s5 = new String("java"); // The intern() method checks if a string with the same value exists in the pool String s6 = s5.intern(); // If it exists, it returns a reference to the object from the pool. // If not, it adds the current string to the pool and returns a reference to it.
Advantages of the string pool:
- Memory saving: Reduces the number of duplicate string objects.
- Performance improvement: Comparing string literals (
==) can be faster than comparingStringobjects withequals(), if both operands refer to the same object in the pool.
Important note:
Comparing strings with the == operator checks whether two variables refer to the same object in memory. To compare the contents of strings, always use the equals() method.
String str1 = "abc"; // In the pool
String str2 = "abc"; // In the pool, same reference
String str3 = new String("abc"); // Outside the pool
String str4 = str3.intern(); // In the pool, same reference as str1 and str2
System.out.println(str1 == str2); // true
System.out.println(str1 == str3); // false
System.out.println(str1 == str4); // true
System.out.println(str1.equals(str3)); // true