Finding the Index of a String in Another String
Your Weekly Java Snippet 004
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!
Last update: May 1, 2026