Equals Method In Java

Java Spring Decoded
Javarevisited
Published in
2 min readApr 10, 2023

In Java equals() method is used to compare equality of two Objects. The equality can be compared in two ways:

Shallow comparison: The default implementation of equals method is defined in Java.lang.Object class which simply checks if two Object references (say x and y) refer to the same Object. i.e. It checks if x == y. Since Object class has no data members that define its state, it is also known as shallow comparison. In This case , we are just comparing the memory location of the two objects , Even if the Objects in this Case contains the same state , it can return false.

Integer i1 = new Integer(10);
Integer i2 = new Integer(10);

Here the two references point to two different objects in heap , resulting false in == operator in java .

Deep Comparison: Suppose a class provides its own implementation of equals() method in order to compare the Objects of that class w.r.t state of the Objects. That means data members (i.e. fields) of Objects are to be compared with one another. Such Comparison based on data members is known as deep comparison. Here we compare the states between the two objects and check if they possess same properties.

Integer i1 = new Integer(10);
Integer i2 = new Integer(10);


@Override
public boolean equals(Integer i1 ,Integer i2){
return i1.intValue() == i2.intValue();

As We can see here , the true equality between two objects of Integer class can be compared with the intValue they associate with , hence by overriding it we Enabled the true equals behaviour.

Some principles of equals() method of Object class : If some other object is equal to a given object, then it follows these rules:

  • Reflexive : for any reference value a, a.equals(a) should return true.
  • Symmetric : for any reference values a and b, if a.equals(b) should return true then b.equals(a) must return true.
  • Transitive : for any reference values a, b, and c, if a.equals(b) returns true and b.equals(c) returns true, then a.equals(c) should return true.
  • Consistent : for any reference values a and b, multiple invocations of a.equals(b) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.

Follow me On Twitter to be Updated on my new Article EveryDay ,

https://twitter.com/JavaUnlocked

--

--

Java Spring Decoded
Javarevisited

All Articles related to java , spring , Backend Development and System Design.