Search code examples
javaequalsequality

The equals implementation in Object


I was reading about the equals method in Java, and I heard people say that == tests for reference equality (whether they are the same object). .equals() tests for value equality (whether they are logically "equal").

I believe it is true but, If you look at the source code for .equals(), it simply defers to ==

From the Object class:

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

Now I am confused. What I see is we are testing if the current object have the same reference to the explicit parameter. Does it test for reference equality or for value equality?


Solution

  • From the Javadoc:

    The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

    Object being the ultimate base class, this is the only definition of equals it can provide. There are no fields to compare across instances, so an instance can only be equal to itself.


    In a comment you've said:

    I would like to know about String comparison I see people use it all the time

    Your question asks about Object, not String. String overrides equals, because Object's definition of equals isn't appropriate for String. Consequently, String defines its own (in keeping with the semantics required for equals implementations).