What is the use of equals method in Java?

Equals method is used when we compare two objects. Default implementation of equals method is defined in Object class. The implementation is similar to == operator. Two object references are equal only if they are pointing to the same object.

== comparison operator checks if the object references are pointing to the same object. It does NOT look at the content of the object.

class Client {
private int id;
public Client(int id) {
this.id = id;
}
}

== comparison operator checks if the object references are pointing to the same object. It does NOT look at the content of the object.

Client client1 = new Client(25);
Client client2 = new Client(25);
Client client3 = client1;
//client1 and client2 are pointing to different client objects.
System.out.println(client1 == client2);//false
//client3 and client1 refer to the same client objects.
System.out.println(client1 == client3);//true

//similar output to ==
System.out.println(client1.equals(client2));//false
System.out.println(client1.equals(client3));//true

We need to override equals method, if we would want to compare the contents of an object

class Client {
private int id;
public Client(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
Client other = (Client) obj;
if (id != other.id)
return false;
return true;
}
}

Consider running the code below:
Client client1 = new Client(25);
Client client2 = new Client(25);
Client client3 = client1;
//both id's are 25
System.out.println(client1.equals(client2));//true
//both id's are 25 System.out.println(client1.equals(client3));//true