Difference between == and .equals in Java.

前端 未结 7 1270
太阳男子
太阳男子 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:27

    Your first example is actually true. The expression in the println just isn't doing what you meant.

    String a = "apple2e";
    String b = "apple2e";
    
    System.out.println("a==b? " + (a == b));
    

    Will print a==b? true note the all important grouping!

    You are correct that a and b are two different references to the same object. This is exactly why == returns true when you test it! == tests if two different pointers point to the same location in memory. Both a and b are references to the same place in memory that holds the interned compile time "apple2e" string.

    Now if you did this

    String a = new String("apple2e");
    String b = new String("apple2e");
    
    System.out.println("a==b? " + (a == b));
    

    It actually will print a==b? false. Because you made two different objects in memory, a and b point to different places.

提交回复
热议问题