As explained in this When should we use intern method of String on String constants post that String literals are automatically pooled but for object constructed using new are not, so for that intern method is used. But even if we use intern method a new object will be created, then what is the use of intern method?
String s = "Example";
String s1 = new String("Example"); // will create new object
String s2 = new String("Example").intern(); // this will create new object
// but as we are calling intern we will get reference of pooled string "Example"
now
System.out.println(s == s1); // will return false
System.out.println(s == s2); // will return true
System.out.println(s1 == s2); // will return false
So what's the use of intern method?
Edit
I understood the working of intern method but my question is why intern method is there? because to call intern method we must create string object using new, which will create new instance of string!
String s3 = new String("Example"); // again new object
String s4 = s3.intern();
System.out.println(s3 == s4); // will return false
So calling intern method will not point s3 to pooled string. intern method will return reference to pooled string.
Also calling intern will push the string into pool if it is not already pooled? So does that mean every time I call intern on any string will be pushed to pool?