The rules about comparison are:
- return a negative number if the first object is considered to be smaller than the second
- return a positive number if the first object is considered to be larger than the second
- return 0 if the two objects are considered to be equally large
In your case there are two factors: length and lexicographical comparison, with length going first. Using your code:
- if the first
string is shorter it is considered to be smaller so you return a negative number (-1)
- if the first string is larger it is considered to be larger so you return a positive number (1)
- if the two string are equally long you consider the lexicographical comparison, as the result of String.compareTo.
I have two improvements for your code:
1) replace lines 8-15 with one line: return s1.compareTo(s2). You don't need the if-else block. After all, if s1.compareTo(s2) returns a negative value you return a negative value; if it returns a positive value you return a positive value; and otherwise you return 0. Since the exact positive / negative values are irrelevant you are essentially returning the same as s1.compareTo(s2).
2) consider using s1.compareToIgnoreCase(s2). This will use case insensitive comparison. With compareTo, "G" is smaller than "a". With compareToIgnoreCase, "G" is larger than "a".