Skip Top Navigation Bar

Using compareTo() to Get the First Name in Alphabetical Order - Example 3

Snippet: Using compareTo() to Get the First Name in Alphabetical Order

Explanation

This snippet puts compareTo() to practical use: finding the alphabetically first name among four strings. The variable firstInAlphabeticalOrder is initialised with "Mary", then each remaining name is compared to it. If a name comes before the current best (i.e. compareTo() returns a negative value), it becomes the new best.

After all comparisons, firstInAlphabeticalOrder holds "James" — the name that comes first in lexicographic order among the four.

What You Can Do

Try adding more names to the list and see if the result still updates correctly. What happens if all names start with the same letter?

You can also try reversing the condition to > 0 instead of < 0 — what does the snippet find then? Can you use this pattern to find both the first and the last name in alphabetical order at the same time?

Run it and observe the output!

Example List

Additional Resources