Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rules for String a == String b [duplicate]

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
}
  1. 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 ?

  2. 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.

like image 389
Ced Avatar asked Jun 08 '16 06:06

Ced


2 Answers

Your s3.intern(); should be s3 = s3.intern(); to get the correct behaviour.

like image 199
Kayaman Avatar answered Nov 02 '22 22:11

Kayaman


  1. 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();

  1. 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.

like image 27
Jesper Avatar answered Nov 03 '22 00:11

Jesper