Equals Method in Java

We can use the equals() method in Java to check the equality of two objects. The equals() method is given to compare two objects of a class for their equality based on their reference or based on data.

The equals() method is defined in java.lang.Object class and compare two objects based on their reference. If both have the same reference then it returns true else it returns false. The implementation of the equals() method in java.lang.Object class is:-

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

Examples:-

public class Test {
   public static void main(String[] args) {

      Test t1 = new Test();
      Test t2 = new Test();
      Test t3 = t1;

      System.out.println(t1.equals(t2));
      System.out.println(t1.equals(t3));
      System.out.println(t2.equals(t3));
   }
}

Output:-

false
true
false

The t1 and t2 are two different objects of Test class, t3 is pointing to the reference of object t1. Hence, t1 and t2 have different references but t3 and t1 are having the same reference.

The equals() method is called on these objects. Since the equals() method is not available in the Test class so, the compiler searches for it in the superclass. Indirectly or directly every valid Java class is the subclass of java.lang.Object class. Hence equals() method will be executed from the Object class which contains logic to compare two objects based on their reference.

Another example:-

class Employee {

   int id;
   String name;

   Employee(int id, String name) {
      this.id = id;
      this.name = name;
   }
}

public class Test {
   public static void main(String[] args) {

      // create objects
      Employee e1 = new Employee(101, "Emma");
      Employee e2 = new Employee(102, "Oliver");
      Employee e3 = e1;

      // display details
      System.out.println(e1.id+" "+ e1.name);
      System.out.println(e2.id+" "+ e2.name);
      System.out.println(e3.id+" "+ e3.name);

      // compare objects
      System.out.println(e1.equals(e2)); // false
      System.out.println(e1.equals(e3)); // true
      System.out.println(e2.equals(e3)); // false
   }
}

Output:-

101 Emma
102 Oliver
101 Emma
false
true
false

If two references are pointing to the object then only equals() method of java.lang.Object class returns true, else they return false.

Overriding equals() Method in Java

If we want to compare two objects with state or value then we must override the equals() method in the subclass. Many times objects are created and passed as method arguments at runtime. So, to know the given object is expected one or not, we must compare objects using their state.

class Employee {

   int id;
   String name;

   Employee(int id, String name) {
      this.id = id;
      this.name = name;
   }

   @Override
   public boolean equals(Object obj) {
      if(this == obj){
         return true;
      }
      if(obj instanceof Employee) {
         Employee e = (Employee) obj;
         return (this.id == e.id) &&
            this.name.equals(e.name);
      }
      return false;
   }
}

public class Test {
   public static void main(String[] args) {

      // create objects
      Employee e1 = new Employee(101, "Emma");
      Employee e2 = new Employee(102, "Oliver");
      Employee e3 = e1;
      Employee e4 = new Employee(101, "Emma");

      // compare objects
      System.out.println(e1.equals(e2)); // false
      System.out.println(e1.equals(e3)); // true
      System.out.println(e1.equals(e4)); // true
   }
}

Output:-

false
true
true

How to Override equals() Method in Java

Step1) While overriding first check the passed object and current object are pointing to the same reference? If both are pointing to the same reference then both objects are always the same.

For this write condition in equals method as,

// compare passed object and current 
// object reference
if(this == obj){
   return true;
}

For example- e1 and e3 are two different objects but they are pointing to the same reference, then it will return true.
Employee e1 = new Employee(101, "Emma");
Employee e3 = e1;
System.out.println(e1.equals(e3)); // true

Step2) Before comparing values of the object, compare both objects are compatible or not. For this we can use instanceof operator.

if(obj instanceof Employee) {
   // logic
} else {
   return false;
}

It will handle situations like comparing with null, or incompatible type objects. Examples:-
Employee e1 = new Employee(101, "Emma");
System.out.println(e1.equals(null)); // false
Test t1 = new Test();
System.out.println(e1.equals(t1)); // false

Step3) Convert object type to current class type.

Employee e = (Employee) obj;

Step4) Finally compare all values of the object.

Here, to compare two primitive values use == operator, and to compare objects use the equals() method. For example, their id and name are two values in the Employee class. Since id is a primitive variable so we will use == operator and name are of String type hence equals() method will be used.

// get current object values
int id1 = this.id;
String name1 = this.name;
// get passed object values
int id2 = e.id;
String name2 = e.name;
// compare values
if((id1 == id2) && (name1.equals(name2)) {
   return true;
}

The current object can be fetched through directly its name or using this keyword. We can reduce the lines as,

return (this.id == e.id) && this.name.equals(e.name);

Or,

return (id == e.id) && name.equals(e.name);

Another Example of Override equals method in Java

Write code to override the equals() method in the given Student class.

class Student {

   private int rollno;
   private String name;
   private String dept;
   private double avg;

   // constructor
   Student(int rollno, String name, 
          String dept, double avg) {
      this.rollno = rollno;
      this.name = name;
      this.dept = dept;
      this.avg = avg;
   }
}

public boolean equals(Object obj) {

   if(this == obj) return true;

   if(obj instanceof Student) {
      Student s = (Student) obj;

      return 
        ( (this.rollno == s.rollno) &&
          this.name.equals(s.name) &&
          this.dept.equals(s.dept) &&
          (this.avg == s.avg) );
   }

   return false;
}

Object Comparison in Java

We can use equals method to compare different types of objects. We have already seen comparison of two different objects.

Comparison using equals()Valid?Return
Two objectsYesfalse/true
Two primitive variablesNocompile-time error
Two nullsNocompile-time error
Null with objectNocompile-time error
Object with nullYesfalse
Null referenced with nullNoNullPointerException
Null referenced with objectNoNullPointerException
Two Null referenced NoNullPointerException
Object with null referencedYesfalse
Incompatible objectsYesfalse
class Employee {

  int id;
  String name;

  Employee(int id, String name) {
    this.id = id;
    this.name = name;
  }
}

public class Test {
  public static void main(String[] args) {

    // Comparing two objects
    Employee e1 = new Employee(101, "Emma");
    Employee e2 = new Employee(102, "Oliver");
    System.out.println(e1.equals(e2)); // false
    Employee e3 = e1;
    System.out.println(e1.equals(e3)); // true

    // Comparing two primitive values
    int x = 9, y = 18;
    System.out.println(x.equals(y)); // error
    // error: int cannot be dereferenced

    // Comparing two nulls
    System.out.println(null.equals(null)); // error
    // error: <null> cannot be dereferenced

    // Comparing null with object
    Employee e4 = new Employee(101, "Emma");
    System.out.println(null.equals(e4)); // error
    // error: <null> cannot be dereferenced

    // Comparing object with null
    Employee e5 = new Employee(101, "Emma");
    System.out.println(e5.equals(null)); // false

    // Comparing null reference with null
    Employee e6 = null;
    System.out.println(e6.equals(null)); // exception
    // java.lang.NullPointerException

    // Comparing null reference with object
    Employee e7 = null;
    Employee e8 = new Employee(102, "Oliver");
    System.out.println(e7.equals(e8)); // exception
    // java.lang.NullPointerException

    // Comparing two null referenced
    Employee e9 = null;
    Employee e10 = null;
    System.out.println(e9.equals(e10)); // exception
    // java.lang.NullPointerException

    // Comparing object with null referenced
    Employee e11 = new Employee(102, "Oliver");
    Employee e12 = null;
    System.out.println(e11.equals(e12)); // false

    // Comparing two incompatiable objects
    Employee emp = new Employee(102, "Oliver");
    Test t = new Test();
    System.out.println(emp.equals(t)); // false
  }
}

Output after commenting each invalid statement,

false
true
false
false
false

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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