Difference between == operator and equals() method in Java

In this post, we will discuss the difference between == operator and equals() method in Java.


 

The == is a relational operator in Java which is used to compare primitive types such as int, double, char, float, etc. It should not be used to compare two object references since for any non-null reference values x and y, x == y returns true only when x and y refers to the same object.

equals(), on the other hand is a method in the Object class which is used for comparing objects. It behaves similar to the == operator if not overridden by a class. Every class should override the equals() method of the Object class and specify the equivalence relation on objects. The equivalence relation should be such that equals() methods evaluates to the comparison of values in the objects irrespective of the two objects refer to the same instance or not. Since equal objects must have equal hash codes, it is necessary to override the hashCode() method as well.

 
Since String is an object in Java, we should always use equals() method for comparing two strings in Java. This works since the String class overrides equals() method of the Object class.

 

 
As evident from the above program, comparing two strings using == and equals() method returns different output. This is because == is performing a reference comparison, i.e. comparing if two variables refer to the same object or not. Since we’re creating two new String objects using String constructor, they will not share the same reference and s1 == s2 returns false. Hence, we should never use == operator for comparing two strings.

On the other hand, equals() method of String class compares the contents of the backed char array and returns a boolean value as a result of the comparison.

 
However below code gives different results. This is because String literals are stored in String constant pool, and both s1 & s2 will share the same reference. So s1 == s2 returns true.

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of