What is the string pool in Java and what does intern() do?
Equal string literals share one object from the string pool. A string made with new is a separate object on the heap. intern() returns the pooled version.
public class Main {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
String d = c.intern();
System.out.println(a == b); // same pooled object
System.out.println(a == c); // c is a different object
System.out.println(a == d); // intern gives the pooled one
System.out.println("ja" + "va" == a); // joined at compile time: pooled
}
}
Output
true
false
true
true
Always compare content with equals(). See Java Strings.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |