String comparison with logical operator in Java

前端 未结 7 1118
别那么骄傲
别那么骄傲 2020-12-03 23:59

When comparing two strings, I was taught that we shouldn\'t use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the fo

7条回答
  •  生来不讨喜
    2020-12-04 00:05

    It works in your case (and AFAIK it has been working like that in earlier JVMs as well) because s refers to the string literal "hello". String references initialized with literals refer to the literal (which is a global object in the background), not a separately created new object. The term for this, as others have mentioned too, is interning. Thus s and "hello" in your example refer to the same physical object. Consider

    String s1 = "hello";
    String s2 = "hello";
    String s3 = "hello";
    

    All of these strings refer to the same physical object, thus '==' comparison between any pair of these, or between any of them and "hello" returns true.

    However

    String s4 = new String ("hello");
    

    creates a new object, thus s4 == "hello" yields false.

提交回复
热议问题