A pool of Strings is maintained by the String class, when the intern() method is invoked, For any two given strings S1 & S2, S1.intern( ) == S2.intern() only if S1.equals(S2) is true.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
For example
public class StringDemo
{
public static void main(String[] args)
{
String S1 = new String("Hello");
String S2 = new String("Hello");
String S3 = "Hello";
String S4 = "Hello";
String S5 = "Hello World";
System.out.println("S1 and S2 comparison:");
System.out.println(S1==S2); //Output: false
System.out.println(S1.equals(S2)); //Output: true
System.out.println(S1.intern()==S2.intern()); //Output: true
System.out.println("S3 and S4 comparison:");
System.out.println(S3==S4); //Output true
System.out.println(S3.equals(S4)); //Output: true
System.out.println("S1 and S3 comparison:");
System.out.println(S1==S3); //Output: false
System.out.println(S1.equals(S3)); //Output: true
System.out.println(S1.intern()==S3.intern()); //Output: true
System.out.println("S1 and S5 comparison:");
System.out.println(S1==S5); //Output: false
System.out.println(S1.equals(S5)); //Output: false
System.out.println(S1.intern()==S5.intern()); //Output: false
}
}
Comments