Java equals method - Tutorial


All classes in Java are child classes of the Object class that you can find in java.lang package in rt.jar. If you open the Object class, you will see that it has many methods and one of the very important ones that we are going to discuss in this tutorial is the equals(Object obj) method.

Let's open the java.lang.Object class and look at the default implementation of the equals method.

Default implementation of equals method in Object class:
public boolean equals(Object obj) {
        return (this == obj);
    }

As you can see, the default implementation uses double equals-to == comparison of the current object and the object passed on to the equals method. == does the address comparison

Example without overriding equals method:

public class EqualsExampleJava {
    
public static void main(String[] args) {
        Employee employee1 = new Employee(1, "Sam");
        Employee employee2 = employee1; //same reference
        Employee employeeDup = new Employee(1, "Sam");

        System.out.println("employee1 == employee2 => " + (employee1 == employee2));
        System.out.println("employee1.equals(employee2) => " + employee1.equals(employee2));

        System.out.println("employee1 == employeeDup => " + (employee1 == employeeDup));
        System.out.println("employee1.equals(employeeDup) => " + employee1.equals(employeeDup));


    }
}

class Employee {

    int employeeId;
    String employeeName;

    Employee(int employeeId, String employeeName) {
        this.employeeId = employeeId;
        this.employeeName = employeeName;
    }
}
Output:

employee1 == employee2 => true
employee1.equals(employee2) => true

employee1 == employeeDup => false
employee1.equals(employeeDup) => false

You will get the same results when comparing two objects using == and equals methods if you do not override the equals method.

✏️ Always compare two objects (created using the new keyword) using the equals(Object obj) method and by overriding it in your class.

In our example, we say that two employees are the same if their name and id are the same,

Example: override equals method
@Override
public boolean equals(Object obj) {

        //If object is null then they are not same
        if(obj == null) return false;

        //If object is have the same reference they are same
        if(obj == this) return true;

        Employee employee = (Employee) obj;

        return this.employeeId == employee.employeeId &&
                 this.employeeName.equals(employee.employeeName);

}
Output:

employee1 == employee2 => true
employee1.equals(employee2) => true

employee1 == employeeDup => false
employee1.equals(employeeDup) => true



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap