equals() method in Java to check if two objects are equal.

Two objects are considered to be equal when they are identical (contain the same data) or in other words they are in the same state.

In order to compare two objects for equality, we need to override equals() method because it is originally defined in Object class that takes a parameter of type Object and compares it with this reference.

It does not make member level comparison. Following is the piece of code of equals() method from Object class.

Sample of equals() method

The above implementation of equals() will only return true if two references point to the same object in memory because it compares memory locations with == operator rather than comparing contents.

If two objects having same data are stored at different locations in memory then above implementation will return false. So, when we define our own data types (classes), we need to override equals().

Equals Method and Operator
Equals Method and Operator

Java’s convention is that equals() must be an equivalence relation. Therefore, overridden equals() method must have the following properties:

  1. Reflexive: x.equals(x) is true.
  2. Symmetric: x.equals(y) is true if and only if y.equals(x).
  3. Transitive: if x.equals(y) and y.equals(z) are true, then so is x.equals(z).

In addition to the above rules, equals() must take an Object as argument and satisfy the following properties.

  1. Consistent: multiple invocations of x.equals(y) consistently return the same value, provided neither object is modified.
  2. Not null: x.equals(null) returns false.

Leave a Reply

Your email address will not be published. Required fields are marked *