Comparing Strings: compareTo 🌶️🌶️
equals answers a yes-or-no question: do these two Strings hold the same characters? compareTo answers a richer one: which of these two Strings comes first?a.compareTo(b) returns an int, and what matters is its sign:
| Return value | Meaning |
|---|---|
| a negative number | a comes before b |
exactly 0 | a and b are equal |
| a positive number | a comes after b |
A useful way to hold onto that: the result describes what
a does relative to b, and negative means earlier.Two things about the ordering itself that are easy to get wrong, and that this worksheet spends most of its time on:
- When one String is a prefix of the other, the shorter one comes first —
"art"comes before"artist". - The ordering is by character code, not by everyday alphabetical rules. Every uppercase letter comes before every lowercase letter, because
AthroughZsit at codes 65-90 whileathroughzsit at 97-122. This one genuinely catches people out.
1. Is the sign of "apple".compareTo("banana") negative, zero, or positive? Type one word, in lowercase.
negative
2. Is the sign of "banana".compareTo("apple") negative, zero, or positive? Type one word, in lowercase.
positive
3. What exact value does "apple".compareTo("apple") return? Type the number.
0
4. Is the sign of "art".compareTo("artist") negative, zero, or positive? ("art" is the first three letters of "artist".) Type one word, in lowercase.
negative
5. Is the sign of "apple".compareTo("Banana") negative, zero, or positive? Read the capitalization carefully. Type one word, in lowercase.
positive
6. Based on the previous question, which of these correctly describes how Java orders letters?
7. You are told that "apple".compareTo("banana") returns exactly -1. What can you safely rely on in the code you write?
8. You have two Strings, a and b, and want a boolean that is true when a comes before b. Which expression gives you that?
9. Put these four Strings into the order Java would sort them with compareTo — first to last. Read the capitalization on each one very carefully; it matters more than you might expect.
Click a placed item to send it back. With drag-and-drop enabled, you can also drag items to reorder them — indent arrows always stay click-only.
10. When you only need to know whether two Strings are equal, why is a.equals(b) usually the better choice than a.compareTo(b) == 0?
Your score for your class is recorded when you click Submit all — checking individual questions doesn't save it. You can submit again to improve your score; your best one counts.