Difference between == and .equals in Java.

前端 未结 7 1349
太阳男子
太阳男子 2021-01-14 12:11

I know this has been covered but I\'ve seen inconsistent arguments here on SO.

So if I have:

String a = \"apple2e\";
String b = \"apple2e\";

System.         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-14 12:40

    a == b looks to see if the two objects point to the same object in memory. Because they don't, even though their internals are the same, a == b will be false. 1 == 1 will be true though, because integers are primitive variables, while Strings are actually objects.

    a.equals(b) is an instance method that internally checks to see if the two strings have the same characters.

    If you did:

    String a = "hello";
    String b = a;
    

    Then a == b would be true.

提交回复
热议问题