This question already has an answer here:
- How do I compare strings in Java? 23 answers
When i see the implementation of equals()
method it does nothing but same as what ==
does. So my question is what was the need to have this as separate method when we have ==
operator which does the same work?
In case of primitives, the
==
operator checks if two values are the same.If it aren't primitives, it checks if it are two pointers (or references) pointing to the same instance of an object.
The
equals()
method performs a custom check, which is inObject
checking the reference, by using==
. But in other classes, sometimesequals()
is overridden (I don't know if this is a correct past participle).equals()
have to check the content.So, for example:
But if we have non-primitives
So, why
str0.equals(str1)
returnstrue
? Because the String class has an override ofequals()
. And in that method it doesn't check if they are equal by doingreturn this == obj;
But in that method, there is a full check. I don't know which method they use to compare the two strings, but here are two possible ways:int == int
)So I hope this is clear now.
There is a very important difference between the two.
"==" compares object instances. The default equals() implementation does this, also. Please run & analyse the following code sample:
As you can see, "==" will return false (the objects are two different instances of Person), whereas equals will return true (because we defined that 2 Persons are equal when they have the same name)