I'm trying to understand how the String pool works and what are the rules for a string to be equal to another String.
For example this snippet :
public static void main(String[] hi){
String s1 = "lol";
String s2 = "lol";
String s3 = new String("lol");
System.out.println( s1 == s2 );// true
System.out.println( s2 == s3); // false
s3.intern(); //line 1
System.out.println( s1 == s3); // false
testString(s1);
}
private static void testString(String s1){
String s4 = "lol";
System.out.println( s1 == s4); // true
}
At //line 1: the string is added to the string pool. Since it's not equal to s1 I assume there is a duplicate in the string pool. Correct ?
What is the rule for having a duplicate in the pool ? In other words when does
someString == someString
return false even though both string have the same char sequence ?
PS: I use string1.equals(string2) everywhere no matter what. I just want a deeper understanding of the underlying mechanism.