Junior — Middle
What strings are stored in the string pool in Java?
sobes.tech AI
Answer from AI
In Java, the String Pool is a special area of memory where string literals and strings created using the intern() method are stored. The pool contains strings that are immutable and unique, meaning if two strings have the same value, only one copy is stored in the pool.
Strings are placed in the pool:
- All string literals, for example, "hello".
- Strings explicitly placed in the pool using the
intern()method.
This helps save memory and speeds up string comparison, as references can be compared instead of contents.
Example:
String s1 = "test"; // string literal, stored in the pool
String s2 = new String("test"); // object created in the heap
String s3 = s2.intern(); // s3 refers to the string from the pool
System.out.println(s1 == s3); // true, both references point to the pool
System.out.println(s1 == s2); // false, different objects