Java equals() Method vs == Operator – Key Differences

equalsjava

I know that equals() will compare the value of objects, the '==' operator will check if the variable point to the same memory.

I do not understand how equals() compare the value of objects, for example:

class Test {
    public Test(int x, float y) {
        this.x = x;
        this.y = y;
    }

    int x,
    float y;
}

Test test1 = new Test(1,2.0);
Test test2 = new Test(1,2.0);

So if I use equals(), will it compare each properties in each object?

And what about if we are talking about String? using equals() and operator “==”, do we still need to override the equals()?

Best Answer

No, if you don't override the equals-method in your class, then equals is the same as ==. See the documentation for this:

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).

The documentation also states what requirements there are for equals methods in case you want to implement it.

Related Question