Explain the difference between "==" in Java and equals of

  • 2020-06-01 09:52:58
  • OfStack

The difference between "==" and equals() in Java

For the relational operator "==," Java programming ideas describes it this way: "the relational operator generates an boolean result that evaluates the relationship between the operand values." The "value" of the operand here is worth noting. For the eight basic data types (boolean, byte, char, short, int, float, double, long), their variables store "values" directly. Therefore, when we use "==" to compare variables of basic data types, what we are actually comparing are the values stored by variables, such as:


public static void main(String[] args) {
    int a = 5, b = 5;
    System.out.println(a == b);
  }

Obviously, the program will output: true. But what about this code?


public static void main(String[] args) {
    Integer c = new Integer(5), d = new Integer(5);
    System.out.println(c == d);
  }

We ran the program and found that the output was: false. This is because Integer is not the basic data type in Java. Its variables c and d are referred to as references to objects in Java. The "value" stored in Integer is the address of the object in memory, not the value "5" itself. Therefore, what c and d actually store are the addresses of two value objects with the value of "5" respectively. These two objects are not in the same memory space as 1 block. The result of "==" comparison is false naturally.

So what does the equals() method compare? equals() is a method defined in the base class Object. In the class Object, the equals() method is defined as:


public boolean equals(Object obj) {
    return (this == obj);
  }

This is equivalent to "==". The point of the equals() method is to override it, otherwise the call to equals() would be meaningless. For example, the Integer class inherited from Object overrides the equals() method:


public boolean equals(Object obj) {
    if (obj instanceof Integer) {
      return value == ((Integer)obj).intValue();
    }
    return false;
  }

The significance of this method is to compare the value value, so if we call equals() for two Integer objects with the same value value:


public static void main(String[] args) {
    Integer c = new Integer(5), d = new Integer(5);
    System.out.println(c.equals(d));
  }

The result is true.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: