Junior — Middle
What is a string pool and why is it needed for storing strings in Java?
sobes.tech AI
Answer from AI
String Pool in Java is a special storage for string literals, where unique instances of strings are stored. When a string is created via a literal, the JVM checks if such a string already exists in the pool. If it does, it returns a reference to it; if not, it adds a new one.
Why is this needed:
- Memory saving: identical strings are stored in one instance, not duplicated.
- Improved string comparison performance: references (==) can be compared instead of content.
Example:
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); // true, both refer to the same object in the pool
String s3 = new String("hello");
System.out.println(s1 == s3); // false, s3 is a new object outside the pool
To explicitly add a string to the pool, you can call the intern() method on the string.