Difference between == and equals in java

The == sign and the equals() method are both methods for comparing equality, so what is the difference and connection between them?
First, the == sign compares values ​​when comparing primitive data types, while the == sign compares the address values ​​of two objects when comparing two objects:

int x = 10;
int y = 10;
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(x == y); // 输出true
System.out.println(str1 == str2); // 输出false
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

What about the equals() method? We can know by looking at the source code that the equals() method exists in the Object class, because the Object class is the direct or indirect parent class of all classes, that is to say, the equals() methods in all classes inherit from the Object class, and pass In the source code, we found that the equals() method in the Object class relies on the == sign at the bottom. Then, in all classes that do not override the equals() method, calling the equals() method has the same effect as using the == sign. The address value of the comparison, however, most of the classes provided by Java have rewritten the equals() method. The rewritten equals() method generally compares the values ​​of two objects:
write picture description here
here I define it myself A Student class, without overriding the equals() method, the final output is: false

write picture description here
After I override the equals() method, the output becomes true.

Now that some basics have been covered, let's go back to the first example:

String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
  • 1
  • 2
  • 3
  • 4

According to the above, the first one is true and the second is false, which is true, then continue to see the following example:

String s1 = "abc";
String s2 = "abc";
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
  • 1
  • 2
  • 3
  • 4

Is the result the same as the previous one? The answer is: true true
why the second one is true?
This involves the constant pool in memory. The constant pool is part of the method area. When running to s1 to create an object, if there is no constant pool in the constant pool, an object "abc" is created in the constant pool, and when it is created for the second time , just use it directly, so the objects created twice are actually the same object, and their address values ​​are equal.

that in the previous example

String str1 = new String("abc");
  • 1

It is how it happened?
In fact, two objects are created here, one is to create the object "abc" in the constant pool, and one is to create the object str1 in the heap memory, so the address values ​​of str1 and str2 are not equal.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325993468&siteId=291194637