Java: Why can String equality be proven with ==?

后端 未结 3 1223
野的像风
野的像风 2020-12-06 17:46

I learned that it is from the devil to test String equality with == instead of String.equals(), because every String was a reference to its own obj

3条回答
  •  悲&欢浪女
    2020-12-06 18:19

    Look, this is a tricky concept.

    There is a difference between:

    // These are String literals
    String a = "Hiabc";
    String b = "abc";
    String c = "abc";
    

    and

    // These are String objects.
    String a = new String("Hiabc");
    String b = new String("abc");
    String c = new String("abc"); 
    

    If your strings were objects, i.e.,

    String b = new String("abc");
    String c = new String("abc");
    

    Then, two different objects would have been created in the String pool at two different memory locations and doing

    b == c  
    

    would have resulted false.

    But since your String b and String c are literals,

    b == c  
    

    results true. This is because two different objects were not created. And both a and b are pointing to same String in the stack memory.

    This is the difference. You are right, == compares for memory location. And that is the reason,

    a.substring(2, 5) == b; // a,substring(2, 5) = "abc" which is at the location of b, and
    b == c // will be true, coz both b and c are literals. And their values are compared and not memory locations.
    

    In order to have two separate Strings with same values but at different locations in the String pool and NOT stack memory, you need to create String objects as shown above.

    So,

    a.substring(2, 5) == b; // and
    b == c; // will be false. as not both are objects. Hence are stored on separate memory locations on the String pool.
    

    you have to use

    a.substring(2, 5).equals(b);
    b.equals(c);
    

    in case of objects.

提交回复
热议问题