This post will discuss how to compare two objects in Java.

You should never use the == operator for comparing two objects, since the == operator performs a reference comparison and it simply checks if the two objects refer to the same instance or not. The recommended option to compare two objects is using the equals() method. However, simply calling the equals() method won’t work as expected, as shown below:

Download  Run Code

 
The above program will call the equals() method of the Object class, which behaves similar to the == operator as it is not overridden by a class. Therefore, every class should override the equals (and hashCode) method of the Object class and specify the equivalence relation on objects, such that it evaluates the comparison of values in the object irrespective of whether two objects refer to the same instance or not. See this post for more details.

Here’s a simple program that demonstrates the working of the equals() method.

Download  Run Code

 
You must also override the hashCode() method, since equal objects must have equal hash codes. If you prefer not to override the equals() and hashCode() method, you can create a custom function to check for equality. This is demonstrated below:

Download  Run Code

That’s all about comparing two objects in Java.