If == compares references in Java, why does it evaluate to true with these Strings?

前端 未结 5 1264
余生分开走
余生分开走 2020-12-06 01:27

As it is stated the == operator compares object references to check if they are referring to the same object on a heap. If so why am I getting the \"Equal\" for this piece o

5条回答
  •  借酒劲吻你
    2020-12-06 02:11

    This code won't print Equal.
    But if the two strings were the same, this case would be special.

    Now that you've updated your code, it is the case :

    A simple (but not totally exact) explanation is that the compiler see that the two strings are the same and do something like :

    String str1 = "Str1";
    String str2 = str1;
    

    What really happens here is that the compiler will see the literal string and put it in the "String literal pool".

    As a String can't be modified (it's immutable) the literal values of Strings (those found during compilation) are put in a "pool".
    This way, if two different literal strings which have the same content (like in this particular case), the memory isn't wasted to store "Str1" and "Str1" two times.

提交回复
热议问题