Over a million developers have joined DZone.

How String equals Method Works

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

The 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 method 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.

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Sandeep Bhandari .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}