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.
Your s3.intern();
should be s3 = s3.intern();
to get the correct behaviour.
- 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 ?
No, not correct. There is already a string "lol" in the string pool, so it's not going to create a duplicate. However, you are not doing anything with the return value of the call to intern()
so s3
is still referring to the String
object that is not in the pool.
Try s3 = s3.intern();
instead of just s3.intern();
- 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 ?
The whole point of the String pool is to avoid duplicate strings in memory, so there will not be any duplicates in the String pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With