Objects that have an ordering are compared using the compareTo() method.
11. All the Rules
"bugbear" .compareTo ("Bugbear") positive "rugrat" .compareTo ("rugRat") positive "ant" .compareTo ("turtle") negative "toadstool" .compareTo ("total") negative "ABCDEFG" .compareTo ("ABcD") negative "roadrunner" .compareTo ("roadkill") positive
All the Rules
Here are all the rules for comparing strings:
Rule 1: If
A.compareTo(B) == 0, then
Bare the same length (counting all characters, including blanks and punctuation) and each character in
Ais identical (including case) to the character in
Bat the same location.
Rule 2: Otherwise, if string
Ais a prefix of string
A.compareTo(B) < 0. If
Bis a prefix of string
A.compareTo(B) > 0.
Rule 3: Otherwise, find the first differing pair of characters in the strings
B. Call them
A.compareTo(B)is negative if
Bcharin 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: