What is the difference between "==" and equals method?

The ==  operator is specifically used to compare whether the values ​​of two variables are equal, that is, to compare whether the values ​​stored in the memory corresponding to the variables are the same, to compare two basic types of data or two reference variables are equal, Only the == operator can be used.

If the data pointed to by a variable is of the object type, then two pieces of memory are involved. The object itself occupies one piece of memory (heap memory), and the variable also occupies one piece of memory, for example, Objet obj = new Object();

The variable obj is a memory, and new Object() is another memory. At this time, the value stored in the memory corresponding to the variable obj is the first address of the memory occupied by the object.

For variables that point to an object type, if you want to compare whether two variables point to the same object, that is, to see whether the values ​​in the memory corresponding to the two variables are equal, then you need to use the == operator for comparison.

 

The equals method is used to compare whether the contents of two independent objects are the same. It is like comparing the appearance of two people. The two objects it compares are independent.

String str1 = new String("Runoob");

String str2 = new String("Runoob");

Two new statements create two objects, and then use the two variables str1 and str2 to point to one of the objects, which are two different objects.

Their first addresses are different, that is, the values ​​stored in str1 and str2 are not the same, so the expression str1 == str2 will return false,

The contents of these two objects are the same, so the expression str1.equals(str2) will return true.
 

 

String in java is a reference data type

String str1 = "Runoob";

String str2 = "Runoob";

String str3 = new String("Runoob");

Why str1 == str2   returns  true

And str1 == str3   returns  false

 

String str1 = "Runoob"; //This is an object created in the static data area

String str2 = "Runoob"; //To create a static data object, first look it up in the static data area, if it exists, do not create a new one, and ensure that there is only one copy of the data in the static data area

String str3 = new String("Runoob"); //Create an object in the heap

str1 == str2 returns true //the objects pointed to are the same

str1 == str3 returns false //The object pointed to is different, the reference value is of course different

 

Stirng is special in that if it exists in the static data area, then it does not create a new object, but points to this object.

 

 

Guess you like

Origin blog.csdn.net/qq_43191910/article/details/114731390