Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What's the difference between s and equals in Java?


May 28, 2021 Article blog



Java is no stranger, so do you understand the difference between == equals This article tells you

== an operator of Java, and there are two ways to compare it

For the basic data type, == judgment of is whether the values on both sides are equal

public class DoubleCompareAndEquals {

    Person person1 = new Person(24,"boy");
    Person person2 = new Person(24,"girl");
    int c = 10;

    private void doubleCompare(){

        int a = 10;
        int b = 10;

        System.out.println(a == b);
        System.out.println(a == c);
        System.out.println(person1.getId() == person2.getId());

    }
}

For the reference type, == judgment is whether the quotation marks on both sides are equal, that is, whether both objects point to the same memory area

private void equals(){

  System.out.println(person1.getName().equals(person2.getName()));
}

equals is the parent class of any object in Java, which is the method defined by the Object class. equals can only compare objects to indicate whether the values of the references are equal. It's important to remember here that it's not == whether the references are equal or not, equals are about equals and you need to distinguish between them.

equals as a comparison between objects has the following characteristics

  • 自反性 For any non-empty reference (x), x.equals(x) returns true
  • 对称性 For any non-empty references (x) and (y), if x.equals (y) is true, then y.equals (x) is also true
  • 传递性 For any non-empty reference value, there are three values: x, y, and z, and if x.equals (y) returns true and y.equals (z) returns true, then x.equals (z) should also return true.
  • 一致性 For any non-empty references x and y, if x.equals(y) are equal, they must always be equal.
  • 非空性 For any non-empty referenced value x, x.equals (null) must return false.

That's what's the difference between Java and equals that the little editor has compiled for you? the whole content