"bugbear" | .compareTo | ("Bugbear") | positve |
"rugrat" | .compareTo | ("rugRat") | positve |
"ant" | .compareTo | ("turtle") | negative |
"toadstool" | .compareTo | ("total") | negative |
"ABCDEFG" | .compareTo | ("ABcD") | negative |
Here are all the rules for comparing strings, in one annoying list:
Rule 1: If
A.compareTo(B) == 0
, thenA
andB
are the same length (counting all characters, including blanks and punctuation) and each character inA
is identical (including case) to the character inB
at the same location.
Rule 2: Otherwise, if string
A
is a prefix of stringB
, thenA.compareTo(B) < 0
. IfB
is a prefix of stringA
, thenA.compareTo(B) > 0
.
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 used by Java (and otherwise is positive).
The rules about what character comes first in the alphabet depend on what country you are in. This is one of the aspects of internationalization, which is the subject of customizing programs for use in different countries. Lets not worry about that.
Of course, you would like to practice this: