Tuesday, 26 March 2013

How String equals method works

       equals method is declared in Object class and hence is inherited by all classes in Java. The purpose of equals method is to provide logical equality. The default implementation of equals method is:


public boolean equals(Object obj) {
return (this == obj);
}

Thus the default behavior of equals method is same as == operator.

equals method in String class checks if the two strings have same characters or not. But this check is performed intelligently. The algorithm for checking the Strings for equality involves:

a) If the String objects are equals as per == operator, true is returned.
b) If the == returns false then each character of both the strings are compared and if a difference if found, immediately false is returned.
c) If after comparing all characters of both the strings, no difference is found in characters and length of strings, true is returned.

Please note that the equals method in String class in Java is case-sensitive. The complete code for equals methos is reproduced here for reference:


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;
}


Also the compareTo method in String class is consistent with equals method.

No comments:

Post a Comment