Junior — Middle
How can you access a string object from the string pool in Java?
sobes.tech AI
Answer from AI
In Java, string literals are stored in the String Pool for memory optimization. To access a string object from the String Pool, you can use the intern() method of the String class.
The intern() method returns a string from the pool if it already exists, or adds the current string to the pool and returns it.
Example:
String s1 = new String("hello");
String s2 = s1.intern(); // s2 refers to the string from the pool
String s3 = "hello"; // string literal from the pool
System.out.println(s2 == s3); // true
Thus, intern() allows you to get a reference to a string from the String Pool.