Finding the Index of a String in Another String
Your Weekly Java Snippet 005
Snippet: Using compareTo() to Get the Rank of a Name in Alphabetical Order
Explanation
This snippet uses compareTo() to compute the rank of "Mary" among the four names. The variable indexOfMary starts at 1, and for each name that comes before "Mary" (i.e. mary.compareTo(other) > 0), the rank is incremented.
"James" comes before "Mary", so indexOfMary becomes 2. "Michael" and "Patricia" both come after "Mary", so they do not increment the counter. The result is 2 — Mary is the second name in alphabetical order.
What You Can Do
Try computing the rank of "Michael" or "Patricia" using the same approach. Do the ranks of all four names together cover exactly 1, 2, 3, and 4?
You can also try adding a fifth name and updating the comparisons. Does the rank of "Mary" change?
Run it and observe the output!
Last update: May 1, 2026