The equals() method

The method equals() of the java.lang.Object class looks like this:

public boolean equals(Object obj) {
//compares references of the current object
//and the reference obj
}

Here is an example of its usage:

Car car1 = new CarImpl();
Car car2 = car1;
Car car3 = new CarImpl();
car1.equals(car2); //returns true
car1.equals(car3); //returns false

As you can see from the preceding example, the implementation of the default method equals() compares only memory references that point to the addresses where the objects are stored. That is why the references car1 and car2 are equal – because they point to the same object (same area of the memory, same address), while the car3 reference points to another object.  

A typical re-implementation of the equals() method uses an object's state for comparison instead. We will explain how to do this in Chapter 6, Interfaces, Classes, and Objects Construction.