The method compareTo
class String
is used to sort the String
s alphabetically*, not by size. This way we have to "araraaaaaa"
comes before "asa"
, and therefore the compareTo
gives -1, because when comparing the first letter the two String
s are equal (a
) and comparing the second, the r
comes before the s
.
To compare the String
s by size, you should invoke the method length
of String
s and then compare sizes directly. (Suggestion from Marcelo Bonifazio)
It is also worth remembering that whenever we have a.compareTo(b)
returning -1 (or some other negative number) means that a
antecedent b
, if it returns +1 (or some other positive number) then a
happens b
and if it returns 0 then a
and b
are similar. However, the exact definition of "antecede", "succeeds" and "similar" is at the discretion of each class that implements the compareTo
. In the case of the class String
the definition is given by alphabetical ordering*.
(*) - In fact the comparison is not exactly alphabetical, but rather is based on comparison of sequences of numerical values of codepoints Unicode.
If you want to compare the contents of these strings, use
str1.equals(str2);
that returns 'true' if they are equal.– Renan Gomes