Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Classes, Objects and Memory

    Equality and toString

    — = asks identity: "are these two references pointing to the same object?" (For primitives, it compares values.)

    Chapter 9 of 103 min read

    The Plain Picture#

    Two identical twins: are they "the same person"? No. Are they "equal" in looks? Yes. Two different questions — and Java makes you pick which one you're asking.

    The Real Names#

    • == asks identity: "are these two references pointing to the same object?" (For primitives, it compares values.)

    • equals(...) asks equality: "do these two objects represent the same value?"

    • Every class inherits a default equals from Java's root class Object — and the default equals is just ==. String, Integer and the collection classes replace it with a content comparison. Your own classes don't, until you write one.

    Java
    Student a = new Student("Priya", 200);
    Student b = new Student("Priya", 200);
    a == b          // false — two objects
    a.equals(b)     // ALSO false — Student hasn't defined equals, so it's still identity

    How to write equals correctly — and its partner hashCode, and the contract between them that HashMap depends on — needs inheritance, so it's in Object-Oriented Programming (and why it matters for hash maps is in Collections, From the Inside).

    toString — how an object prints#

    Printing an object calls its toString() method. The default one prints the class name and a hash code — useless:

    Java
    System.out.println(new Plain()); // Demo$Plain@8c3b9d

    Define your own and printing becomes readable (the @Override marker is explained in Object-Oriented Programming):

    Java
    @Override
    public String toString() {
        return name + "(" + score + ")";
    }
    // System.out.println(priya);   →   Priya(200)

    Readable toString methods make debugging and logs far easier. Records (Ch 5) generate one for you.

    Check yourself

    3 questions
    1

    == vs equals in one sentence each.

    Show answer

    == checks whether two references point to the same object; equals checks whether two objects are logically equal.

    2

    For your own class with no equals method, what does a.equals(b) do?

    Show answer

    The same as a == b — the inherited default from Object.

    3

    What does printing an object with no toString show?

    Show answer

    The class name, @, and a hex hash code, like Demo$Plain@8c3b9d.