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
- 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