How would you override .equals() to handle custom equality conditions in Java?

To implement custom equality in Java, the equals() method should be overridden to compare the business-relevant fields of an object rather than comparing object references. A proper implementation checks for self-comparison, verifies the object type, and then compares the fields that determine logical equality. Whenever equals() is overridden, hashCode() must also be overridden to maintain the contract required by hash-based collections.

Key Points

Example

In an Employee class, two employee objects may be considered equal if they have the same employeeId, even if they are different object instances in memory. This allows collections to treat logically identical employees as the same entity.

import java.util.Objects;

class Employee {

    private int employeeId;
    private String name;

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

    @Override
    public boolean equals(Object obj) {

        if (this == obj) {
            return true;
        }

        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }

        Employee other = (Employee) obj;
        return employeeId == other.employeeId &&
               Objects.equals(name, other.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(employeeId, name);
    }
}

Interview Tip

A concise interview answer is: To implement custom equality, override equals() to compare the fields that define logical equality, perform proper null and type checks, and use Objects.equals() for safe comparisons. Always override hashCode() together with equals() to maintain consistency in hash-based collections.

Last updated: 1 November 2026

Previous question: Why is immutability considered a beneficial property in multi-threaded applications?

Next question: How would you ensure atomicity without using the synchronized keyword?

More Core Java - Level IV (Advanced) interview questions

All Core Java - Level IV (Advanced) questions