how does default equals implementation in java works for String?
equals, java, string
Solution
Yes by default equals method implements `==` in `Object` class . But you can Override the `equals` method in your own class to change the way `equality` is done between two objects of the same class. For example the `equals` method in `String` class is overridden as follows:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
So this is the reason that for the following code:
String s1 = new String("java");
String s2 = new String("java");
`s1==s2` returns `false` since both are referencing different objects on heap. Whereas `s1.equals(s2)` returns `true` since now the `equals` being called is what defined within `String` class where `String` objects are compared on the basis of `contents` of String.
Problem
We all know if we create two String objects and use == to compare them it will return false and if we use equals to method it will return true. But by default equals method implement == only , then how does it return true , it should return whatever == is returning ??