Using compareTo() to Get the First Name in Alphabetical Order - Example 4
Snippet: Using compareTo() to Get the Last Name in Alphabetical Order
Explanation
This snippet is the mirror of the previous one. Instead of checking < 0 to find the alphabetically first name, it checks > 0 to find the last one. If a name comes after the current best (i.e. compareTo() returns a positive value), it becomes the new best.
Starting from "Mary", each name is compared in turn. "Michael" comes after "Mary", then "Patricia" comes after "Michael", and "James" does not come after "Patricia". So the result is "Patricia" — the name that comes last in lexicographic order.
What You Can Do
Try running this snippet alongside the previous one (snippet 003). Together they find the first and last names — can you combine both into a single pass, updating two variables at once?
You can also try adding a name that starts with a lowercase letter, like "anna". Where does it end up in the order, and does the result surprise you?
Run it and observe the output!
Example List
Additional Resources
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis