Objects that have an ordering are compared using the compareTo() method.
10. First Differing Pair of Characters
"bugbear" .compareTo ("bugbear") zero "bug" .compareTo ("bugbear") negative "pepper" .compareTo ("peppermint") negative "toadstool" .compareTo ("toad") positive "cat" .compareTo ("caterpillar") negative
First Differing Pair of Characters
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:
first differing characters are 'a' and 'e'
first differing characters are 'r' and 'h'
first differing characters are 'c' and 'm'
first differing characters are 'b' and 'B'
Find the first pair of differing characters. The result of
compareTo() is based on just that pair.
Rule 3: Find the first differing pair of characters in the strings
B. Call them
A.compareTo(B) is negative if
Achar comes before
Bchar 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 following:
Comparison Zero, Positive, or Negative "bugbear" .compareTo ("Bugbear") "rugrat" .compareTo ("rugRat") "ant" .compareTo ("turtle") "toadstool" .compareTo ("total") "ABCDEFG" .compareTo ("ABcD") "roadrunner" .compareTo ("roadkill")