Junior — Middle
How can you get a string from the string pool in Java?
sobes.tech AI
Answer from AI
In Java, a string from the string pool is either a string literal or a string explicitly placed in the string pool to save memory.
To get a string from the string pool, you can use the intern() method of the String class.
Example:
String s1 = new String("hello");
String s2 = s1.intern();
// s2 now refers to a string from the string pool
Methods to obtain a string from the pool:
- Using string literals, for example,
String s = "text";— such strings are automatically placed in the pool. - Calling
intern()on a string — if such a string already exists in the pool, a reference to it is returned; otherwise, the string is added to the pool and the reference is returned.
This is useful for saving memory and speeding up string comparison using ==.