Sunday, August 22, 2021

Difference between equals method and "==" operator in Java - Interview Question

Both equals() and "==" operators in Java are used to compare objects to check equality but the main difference between the equals method and the == operator is that the former is a method and the latter is an operator. Since Java doesn’t support operator overloading, == behaves identical for every object but equals() is a method, which can be overridden in Java, and logic to compare objects can be changed based upon business rules. Another notable difference between the == and equals method is that the former is used to compare both primitive and objects while the latter is only used for objects comparison.


At the same time, beginners struggle to find when to use the equality operator (==) and when to use the equals method for comparing Java objects. 

In this tutorial, we will see how the equals() method and == operator works in Java and what is the difference between "==" and equals method in Java, and finally when to use "==" and equals() to compare objects.




What is the "==" equality operator in Java

Difference between == and equals method in Java"==" or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. In terms of comparing primitives like boolean, int, float "==" works fine but when it comes to comparing objects it creates confusion with the equals method in Java.

The equality operator or "==" compares two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false. 

After the introduction of Autoboxing and unboxing in Java 5, using == to compare wrapper objects even become trickier because sometimes they can return an unexpected result. See my post what is the problem with == operator in autoboxing world post-Java 5 for more details.




1. What is the equals method in Java?

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic e.g. two Employees are considered equal if they have the same empId etc. 

You can have your domain object and then override the equals method for defining a condition on which two domain objects will be considered equal. equal has contracted with hashcode method in Java and whenever you override equals method you also need to override hashcode() in Java

The default implementation of equals provided in the Object class is similar to the "==" equality operator and returns true if you are comparing two references to the same object.

It’s one of the Java best practices to override equals in Java to define equality based on business requirements. It’s also worth noting that equals should be consistent with compareTo in Java So that when you store objects in TreeMap or TreeSet Collection, which uses compareTo for checking equality, behavior remains consistent.

Difference between == and equals in Java

The main difference between == and equals in Java is that "==" is used to compare primitives while the equals() method is recommended to check the equality of objects. 

Another difference between them is that, If both "==" and equals() are used to compare objects then == returns true only if both references point to the same object while equals() can return true or false based on its overridden implementation

One of the popular cases is comparing two String in Java in which case == and equals() method return different results.



1. Comparing String with == and equals

String comparison is a common scenario of using both == and equals method. Since java.lang.String class override equals method, It returns true if two String object contains same content but == will only return true if two references are pointing to the same object. 

Here is an example of comparing two Strings in Java for equality using the == and equals() method which will clear some doubts:

String personalLoan = new String("cheap personal loans");
String homeLoan = new String("cheap personal loans");
     
//since two strings are different object result should be false
boolean result = personalLoan == homeLoan;
System.out.println("Comparing two strings with == operator: " + result);
     
//since strings contains same content , equals() should return true
result = personalLoan.equals(homeLoan);
System.out.println("Comparing two Strings with same content using equals method: " + result);
     
homeLoan = personalLoan;
//since both homeLoan and personalLoand reference variables are pointing to the same object
//"==" should return true
result = (personalLoan == homeLoan);
System.out.println("Comparing two reference pointing to same String with == operator: " + result);

Output:
Comparing two strings with == operator: false
Comparing two Strings with the same content using equals method: true
Comparing two references pointing to the same String with == operator: true



2. Comparing two objects with "==" and equals.

Another scenario that creates confusion between the == and equals method is when you compare two Objects. When you compare two references pointing to an object of type Object you should see the same result from both == operator and equals method because the default implementation of equals method just compare memory address of two objects and return true if two reference variable are pointing towards an exactly same object. 

Here is example of == vs equals method for comparing two objects:

Object obj1 = new Object();
Object obj2 = new Object();
     
// == should return false
result = (obj1==obj2);
System.out.println("Comparing two different Objects with == operator: " + result);
     
//equals should return false because obj1 and obj2 are different
result = obj1.equals(obj2);
System.out.println("Comparing two different Objects with equals() method: " + result);
     
// "==" should return true because both obj1 and obj2 points same object
obj1=obj2;
result = (obj1==obj2);
System.out.println("Comparing two reference pointing to same Object with == operator: " + result);

Output:
Comparing two different Objects with == operator: false
Comparing two different Objects with equals() method: false
Comparing two references pointing to the same Object with == operator: true


Summary

1) use == to compare primitive e.g. boolean, int, char etc, while use equals() to compare objects in Java.

2) == return true if two references are of the same object. The result of the equals() method depends on overridden implementation.

3) For comparing String use equals() instead of  == equality operator.


That’s all on the difference between equals method and  == operator in Java.  As I said the main difference between them is that one of them is an operator and the other is a method and == is used to compare both primitive and objects while the equals() method is used to check the equality of objects only.


Other Java Interview questions articles from Javarevisited blog

7 comments :

Sagar said...

class Printdate
{
static int d,m,y;

public Printdate(int d,int m,int y)
{
this.d=d;
this.m=m;
this.y=y;
}

public static void disp()
{
System.out.println(d+"/"+m+"/"+y);
}

public static void main(String[] args)
{
Printdate p =new Printdate(28,11,14);
Printdate e =new Printdate(28,11,14);

if (p.equals(e))
{
System.out.println("Dates are same");
disp();
}
else
{
System.out.println("Dates are different");
System.out.println(p.hashCode());
System.out.println(e.hashCode());
}

}
}
for the above code m getting output as Dates are different.
kindly help me to find my mistake.

Anonymous said...

@sagar if you dont override equals method in your class it behaves as == operator which returns true if objects point same memory address.

Anonymous said...

Sagar is

Vinod Rawat said...

Thanks for the great tutorial. I most often refer to these to enrich my knowledge.
I have a query:
We know == operator perform reference comparison, i.e. both objects point to the same memory location or not.
So if we override equals and hashcode in Object class, and considering both objects have same set of values, then why still below always return false.

result = (obj1==obj2);
System.out.println("Comparing two different Objects with == operator: " + result);

I checked, I am getting same hashcode for both objects when I do sysout on these, but still == comparison is not working.
Could you please shed some light on this.

javin paul said...

Hello Vinod, The logic of == compares memory location and not the hashcode, so even if you override hashCode and return same for every object, == will return false because their reference is not same.

Ajay Thakur said...

package corejava;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Palindrome {

public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter your string");
String str=s.nextLine();
String stray[]=str.split(" ");
String t1="";
String t2="";
String smallpalen="";
ArrayList palen=new ArrayList();
for(int i=0;ipalen.get(k).toString().length()?palen.get(k).toString():smallpalen;
}
System.out.println("smallest palindrome in your string is : "+smallpalen);



}
}
}

hrazin said...

This was a helpful article which answered my question, but there's just one small grammatical issue I noticed while reading this article.
On line 3, the individual who wrote this wrote:
"behaves identical for every object but equals() is method"
This should be:
"behaves identical for every object but equals() is a method"

Post a Comment