This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

It’s easy to understand how and where data and variables are stored in memory. Sometimes you can draw a picture of how it is stored and pointed to in memory, so that you can see at a glance. Secondly, it is more examples to verify, analysis of its differences!

  • The == operator is used to compare whether the values of two variables are equal. That is, it is used to compare whether the values stored in the corresponding memory of the variables are the same. To compare whether two basic types of data or two reference variables are equal, the == operator can only be used. If a variable refers to data of Object type, then two pieces of memory are involved, one for the Object itself (heap) and one for the variable (stack). For example, Objet obj = new Object(); The variable obj is stored on the stack, and the Object new Object() is stored in the heap. In this case, the value stored in the memory corresponding to the variable obj is the first address of the block of memory occupied by the Object. For variables that refer to an object type, if you want to compare whether two variables refer to the same object, that is, whether the values in memory corresponding to the two variables are equal, you need to use the == operator to compare.

  • The equals method is used to compare the content of two independent objects to whether they are identical. It compares two independent objects to whether they look the same. For example, for the following code:

String a=new String("foo");
String b=new String("foo");
Copy the code

Two new statement creates two objects, and then use a, b, the two variables refer to the one of the objects, they are two different objects, the first address is different, which is stored in a and b values are not the same, so the expression a = = b returns false, and that the contents of the two objects are the same, so, The expression a.equals(b) returns true.

If a class does not define its own equals method, it inherits the equals method of the Object class. The equals method is implemented as follows:

boolean equals(Object o){
    return this==o;
}
Copy the code

Equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals equals Always return false if two independent objects are being compared. If you write a class that wants to be able to compare the contents of two instances created by that class, you must override equals and write your own code to determine when the contents of two objects are considered the same.