Thomas Lötzer Thomas Lötzer - 7 months ago 45
Java Question

Java Strings: compareTo() vs. equals()

When testing for equality of strings in Java I have always used equals() because to me this seems to be the most natural method for it. After all, its name already says what it is intended to do. However, a colleague of mine recently told me had been taught to use compareTo() == 0 instead of equals(). This feels unnatural (as compareTo() is meant to provide an ordering and not compare for equality) and even somewhat dangerous (because compareTo() == 0 does not necessarily imply equality in all cases, even though I know it does for Strings) to me.

He did not know why he was taught to use compareTo() instead of equals() for strings, and I could also not find any reason why. Is this really a matter of personal taste, or is there any real reason for either method?


A difference is that "foo".equals((String)null) returns false while "foo".compareTo((String)null) == 0 throws a NullPointerException. So they are not always interchangeable even for Strings.