Junior — Middle
Selgitage StringPool kasutamise põhimõtet ja selle rolli stringide haldamisel Java-s
sobes.tech AI
Vastus AI-lt
Java's StringPool is a special pool of string literals that stores unique instances of strings to save memory and improve performance.
When a string is created using 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:
- Avoiding duplication of identical strings in memory.
- Faster comparison of strings by reference (==), if they come 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