Basic of Java’s equals() and == operator

Neil Holkar
2 min readOct 19, 2019

--

In Java, for the comparison of two objects, equals() and == operator are used.The difference in these two things lies in the very heart of their definition.Lets understand it one by one.

Lets first talk about equals() in Java.Suppose you have following piece of code with you:

Here we have two objects- obj1 and obj2 which are of type MyClass.
The == operator checks for the address of the objects.Internally it checks for the hash code of objects.If hash-code matches i.e both objects are same, then it returns true.
When we compare these two objects in java by either equals() or == , we get the same output because for object comparison, internally the equals() method uses == operator only.

Now take another example of String in Java:

Here we created two String class objects- s1 and s2 and we used equals() and == operator, for there comparison.
Unlike above example, we got different output.Lets understand this:

String Class equals method- Internal Implementation

The String class’s equals() first check the object reference.If both object points to the same object — It returns true.
If both the object are different, then it goes for checking the content of each string — char by char.If both string contains same characters, then it returns true.

NOTE: Internally String Class’s equals method first check for object address only i.e it uses == operator first to check if both string objects are same or not.If both objects are same then it returns true irrespective of the content of the string.
Hence if you either want to check address/reference of two string or content of two strings — ALWAYS GO FOR EQUALS METHOD OF STRING.

--

--

No responses yet