Junior
What is a string pool in Java?
sobes.tech AI
Answer from AI
String Pool — is an area in the JVM heap where string literals are stored. When the JVM encounters a string literal, it first checks this pool. If the string already exists, a reference to the existing object is returned. If not, a new string object is created in the pool and a reference to it is returned.
Advantages:
- Memory saving: Multiple references can point to the same string object in the pool.
- Performance: Comparing references (==) to pool strings is faster than comparing string contents (equals()).
Example:
// Creates a string in the pool (if it is not there yet)
String s1 = "hello";
// Returns a reference to the same "hello" object from the pool
String s2 = "hello";
// s1 and s2 refer to the same object
System.out.println(s1 == s2); // Outputs true
// Creates a new string object "hello" in the heap, not in the pool
String s3 = new String("hello");
// s1 and s3 refer to different objects
System.out.println(s1 == s3); // Outputs false
// The contents of the strings are the same
System.out.println(s1.equals(s3)); // Outputs true
The intern() method can be used to explicitly add a string created with new String() to the pool or to get a reference to an existing string from the pool with the same content.
// Creates a new string object "world" in the heap
String s4 = new String("world");
// Adds "world" to the pool (if it is not there) and returns a reference
String s5 = s4.intern();
// Creates a string in the pool (reference to the same object that s5 now points to)
String s6 = "world";
// s5 and s6 refer to the same object in the pool
System.out.println(s5 == s6); // Outputs true