Skip to lesson

Write your own equals()

equals() decides when two different objects count as equal. Object's version only checks this == obj, so your class overrides it to compare the fields that matter.

Decide what "equal" means

equals() is the Object method public boolean equals(Object obj) that says whether another object is logically equal to this one. Object's version returns this == obj, so a class overrides it to compare the fields that decide equality.

Two Point(1, 2) objects should be equal, but Object's equals(), shown below, says they are not.

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

So first decide which fields make two objects the same: x and y for a point, the roll number for a student, the ISBN for a book.

This choice is a design decision, and Java follows whatever you write. String already made it: its equals() compares the letters. Your own classes need the recipe in the next section.

The standard recipe, step by step

The header must be exactly public boolean equals(Object obj), with @Override. The body runs five checks in a fixed order, from the cheapest to the field comparison.

Example 1 · The recipe in action

PointEqualsDemo.javaJava
class Point {    int x;    int y;
    Point(int x, int y) {        this.x = x;        this.y = y;    }
    @Override    public boolean equals(Object obj) {        if (this == obj) {            return true;        }        if (obj == null) {            return false;        }        if (getClass() != obj.getClass()) {            return false;        }        Point other = (Point) obj;        return x == other.x && y == other.y;    }}
public class PointEqualsDemo {    public static void main(String[] args) {        Point p1 = new Point(1, 2);        Point p2 = new Point(1, 2);        Point p3 = new Point(2, 1);
        System.out.println(p1 == p2);        System.out.println(p1.equals(p2));        System.out.println(p1.equals(p3));        System.out.println(p1.equals(null));        System.out.println(p1.equals("(1, 2)"));    }}
Output
false
true
false
false
false

What this code does

  • p1 and p2 are still two objects (== is false), but now equals() compares x and y and says true.
  • null and a String are handled safely by steps 2 and 3: the answer is false, not a crash.

Example 2 · equals() makes search work

StudentSearchDemo.javaJava
class Student {    String name;    int roll;
    Student(String name, int roll) {        this.name = name;        this.roll = roll;    }
    @Override    public boolean equals(Object obj) {        if (this == obj) {            return true;        }        if (obj == null || getClass() != obj.getClass()) {            return false;        }        Student other = (Student) obj;        return roll == other.roll && name.equals(other.name);    }}
public class StudentSearchDemo {    static int indexOf(Student[] list, Student target) {        for (int i = 0; i < list.length; i++) {            if (list[i].equals(target)) {                return i;            }        }        return -1;    }
    public static void main(String[] args) {        Student[] cls = { new Student("Arjun", 3), new Student("Kavya", 5), new Student("Diya", 7) };        System.out.println(indexOf(cls, new Student("Diya", 7)));        System.out.println(indexOf(cls, new Student("Diya", 8)));    }}
Output
2
-1

What this code does

  • The search uses equals(), so a new object with the same roll and name is found at index 2.
  • The int field uses ==; the String field uses equals(). Steps 2 and 3 are joined with || here, which is a common short form.

The steps: same reference → null → getClass() → cast → compare fields. (Point) obj is a cast: obj is declared as Object, so Java cannot see x through it until you say it is a Point. Step 3 has already made sure, so the cast is safe; Downcasting (opens in a new tab) explains casts in full.

Order of execution

Put the equals() recipe in order

Tap the lines of Point's equals() body in the order they must run.

Comparing each kind of field

Objects.equals(a, b), from java.util.Objects, is a null-safe comparison: it returns true when both are null, false when only one is null, and a.equals(b) otherwise. Use it for object fields that may be null.

Pick the comparison by the field's type: == for int, long, char and boolean; equals() for String and other objects. A field that may be null needs one more step.

Example 3 · Mistake: a null field crashes equals()

NullFieldDemo.javaJava
class Contact {    String name;    String email;
    Contact(String name, String email) {        this.name = name;        this.email = email;    }
    @Override    public boolean equals(Object obj) {        if (this == obj) {            return true;        }        if (obj == null || getClass() != obj.getClass()) {            return false;        }        Contact other = (Contact) obj;        return name.equals(other.name) && email.equals(other.email);    }}
public class NullFieldDemo {    public static void main(String[] args) {        Contact a = new Contact("Rohan", null);        Contact b = new Contact("Rohan", null);        System.out.println(a.equals(b));    }}
Sample output
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "this.email" is null
	at Contact.equals(NullFieldDemo.java:19)
	at NullFieldDemo.main(NullFieldDemo.java:27)

What this code does

  • Rohan has no email, so email is null, and email.equals(...) calls a method on null.
  • The crash happens inside equals(). Code that only compares objects should never crash like this.

Example 4 · Fix: Objects.equals() handles null

ObjectsEqualsDemo.javaJava
import java.util.Objects;
class Contact {    String name;    String email;
    Contact(String name, String email) {        this.name = name;        this.email = email;    }
    @Override    public boolean equals(Object obj) {        if (this == obj) {            return true;        }        if (obj == null || getClass() != obj.getClass()) {            return false;        }        Contact other = (Contact) obj;        return Objects.equals(name, other.name) && Objects.equals(email, other.email);    }}
public class ObjectsEqualsDemo {    public static void main(String[] args) {        Contact a = new Contact("Rohan", null);        Contact b = new Contact("Rohan", null);        Contact c = new Contact("Rohan", "rohan@mail.com");        System.out.println(a.equals(b));        System.out.println(a.equals(c));        System.out.println(c.equals(a));    }}
Output
true
false
false

What this code does

  • Objects.equals(null, null) is true, and Objects.equals(null, "rohan@mail.com") is false: no crash either way.
  • a.equals(c) and c.equals(a) agree, so the "both ways" rule holds.

For double fields, IDEs generate Double.compare(price, other.price) == 0. It treats Double.NaN ("not a number", the result of 0.0 / 0.0) as equal to itself, where plain == says false.

The overload trap: equals(Book other)

It is tempting to write public boolean equals(Book other). That is an overload, a second equals method, not an override, as in Overloading vs overriding (opens in a new tab).

Example 5 · Mistake: equals(Book other) overloads instead of overriding

OverloadBugDemo.javaJava
class Book {    String isbn;
    Book(String isbn) {        this.isbn = isbn;    }
    public boolean equals(Book other) {        return isbn.equals(other.isbn);    }}
public class OverloadBugDemo {    static boolean contains(Object[] items, Object target) {        for (int i = 0; i < items.length; i++) {            if (items[i].equals(target)) {                return true;            }        }        return false;    }
    public static void main(String[] args) {        Book b1 = new Book("978-81");        Book b2 = new Book("978-81");        Object o = b2;        Book[] shelf = { b1 };
        System.out.println(b1.equals(b2));        System.out.println(b1.equals(o));        System.out.println(contains(shelf, b2));    }}
Output
true
false
false

What this code does

  • b1.equals(b2) passes a Book, so Java picks the new equals(Book) and it seems to work.
  • Java picks the method from the declared type of the argument. o and target in contains are Object, so Object's equals(Object) runs, which is still ==.

Example 6 · @Override catches the overload bug

OverrideCheckDemo.javaJava
class Book {    String isbn;
    Book(String isbn) {        this.isbn = isbn;    }
    @Override    public boolean equals(Book other) {        return isbn.equals(other.isbn);    }}
public class OverrideCheckDemo {    public static void main(String[] args) {        System.out.println(new Book("978-81").equals(new Book("978-81")));    }}
Sample compiler output
OverrideCheckDemo.java:8: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error

What this code does

  • With @Override, the compiler checks that the method really replaces a parent method, and equals(Book) does not.
  • Fix: change the header to public boolean equals(Object obj) and use the full recipe.

Java picks an overload from the declared type of the argument. Any code that holds an Object, including Java's own library classes, calls equals(Object), which is still ==. With @Override (opens in a new tab), javac reports the mistake at once.

The equals contract

The equals contract is the set of rules every equals() must keep: reflexive (a.equals(a) is true), symmetric (a.equals(b) == b.equals(a)), transitive (a = b and b = c give a = c), consistent (same answer while fields stay the same), and x.equals(null) is false.

Java code everywhere, including the library classes, trusts these five rules. The recipe keeps all of them, as this check on three equal points shows.

Java
Point a = new Point(2, 3);Point b = new Point(2, 3);Point c = new Point(2, 3);System.out.println(a.equals(a));                             // reflexive: trueSystem.out.println(a.equals(b) == b.equals(a));              // symmetric: trueSystem.out.println(a.equals(b) && b.equals(c) && a.equals(c)); // transitive: trueSystem.out.println(a.equals(null));                          // null: false

Why getClass() and not instanceof in step 3? getClass() is strict: a Person never equals a Student, so the symmetric rule holds even when a subclass adds fields. obj instanceof Point, taught in The instanceof operator (opens in a new tab), also accepts subclass objects; that is safe only while no subclass changes equals().

When you override equals(), also override hashCode(): hashCode() (opens in a new tab) shows why.

Next step

Check your understanding

12 quick questions