When testing for equality of String
's 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 String
's) to me.
He did not know why he was taught to use compareTo()
instead of equals()
for String
's, 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?
"equals" compare objects and return true or false and "compare to" return 0 if is true or an number [> 0] or [< 0] if is false here an example:
Results:
Documentation Compare to: https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
Documentation Equals : https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)