How equals() method works
String
class has overridden the equals()
method . Please follow the String#equals() documentation.
a.equals(b) has returned true, meaning the condition a==b is satisfied
This is the default implementation of equals()
in the Object
class , String
class has overridden the default implementation. It returns true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
Aren't hashCode and address one and same?
Not necessarily , for further reading on hashCode().
No, Hashcode and address aren't the same.
Because a==b is not comparing hashcodes.
Yes, something else is compared when we say a==b.
(that's not addresses either, really, but it's close enough).
Also, just because "equal objects have equal hashcodes" does not mean "equal hashcodes means equal objects".
The ==
operator in Java compares object references to see if they refer to the same object. Because your variables a
and b
refer to different objects, they are not equal according to ==
.
And the hashCode
method doesn't return the address in String
, because that class has overridden hashCode
.
Additionally, the equals
method has been implemented in String
to compare the contents of the strings; that's why a.equals(b)
returns true
here.