Skip Top Navigation Bar

Using compareTo() for String Comparison - Example 1

Snippet: Using compareTo() for String Comparison

Explanation

This snippet introduces compareTo(), which compares two strings lexicographically (i.e. in the alphabetical order). It returns an int with three possible meanings:

  • 0 if the strings are equal — as with mary.compareTo(mary).
  • A negative number if the calling string comes before the argument — "Mary" comes before "Michael", so mary.compareTo(michael) returns a negative value.
  • A positive number if the calling string comes after the argument — michael.compareTo(mary) returns a positive value.

Note that the value of the number is nor meaningful in this case, only the signs count. You only need to know whether the result is negative, zero, or positive.

What You Can Do

Try comparing strings that start with different first letters, like "Apple" and "Banana". Is the sign of the result consistent with alphabetical order?

You can also try comparing strings that differ only in case, like "mary" and "Mary". Does the order surprise you? Lowercase letters comes after uppercase letters, lexicographically.

Run it and observe the output!

Example List

Additional Resources