"bugbear" | .compareTo | ("bugbear") | zero |
"bug" | .compareTo | ("bugbear") | negative |
"pepper" | .compareTo | ("peppermint") | negative |
"toadstool" | .compareTo | ("toad") | positive |
"cat" | .compareTo | ("caterpillar") | negative |
The remaining case is the difficult one. Say that two strings are not identical, and one is not the prefix of the other. Then there must be at least one character in one string that is different from a character at the same position in the other string:
beat | first differing characters are 'a' and 'e' beet bear rug | first differing characters are 'r' and 'h' bear hug batcave |||| first differing characters are 'c' and 'm' batmobile baseball bat | | first differing characters are 'b' and 'B' baseBall hat
Find the first pair of differing characters.
The result of compareTo()
is based on just that pair.
Rule 3: Otherwise, find the first differing pair of characters in the strings
A
andB
. Call themAchar
andBchar
. ThenA.compareTo(B)
is negative ifAchar
comes beforeBchar
in the alphabet that Java uses (and otherwise is positive).
This rule compares just two characters. For characters of the same case, the one that comes earlier in the alphabet that Java uses is less than the other. For characters of different case, all upper case characters are less than all lower case characters.
The lengths of the two strings do not matter. Merely find the first differing pair of characters, and base the result on them.
Decide on the outcomes of comparsions of the following: