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
Java Strings
Java String Methods
Java StringBuilder and Text Blocks
Exercises & Assignments
Reverse a string
Check if a string is a palindrome
Count the vowels in a string
Interview Questions & Answers
What is the difference between == and equals() in Java?
Why is String immutable in Java?
What is the difference between String, StringBuilder and StringBuffer?
What is the string pool in Java and what does intern() do?