According to String#intern(), intern
method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string
By using heap object reference if we want to get corresponding string constant pool object reference, then we should go for intern()
String s1 = new String("Rakesh");
String s2 = s1.intern();
String s3 = "Rakesh";
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // true
Pictorial View
Step 1: Object with data 'Rakesh' get created in heap and string constant pool. Also s1 is always pointing to heap object.
Step 2: By using heap object reference s1, we are trying to get corresponding string constant pool object referenc s2, using intern()
Step 3: Intentionally creating a object with data 'Rakesh' in string constant pool, referenced by name s3
As "==" operator meant for reference comparison.
Getting false for s1==s2
Getting true for s2==s3
Hope this help!!