Junior — Middle
Explain the principle of using StringPool and its role in string management in Java
sobes.tech AI
Answer from AI
StringPool in Java is a special pool of string literals that stores unique instances of strings to save memory and improve performance.
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 the existing one; if not, it adds a new one.
This allows:
- To avoid duplicating identical strings in memory.
- To compare strings more quickly by reference (==) if they are from the pool.
Example:
String a = "hello";
String b = "hello";
System.out.println(a == b); // true, both refer to the same object in StringPool
String c = new String("hello");
System.out.println(a == c); // false, c is a new object outside the pool