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:
0if the strings are equal — as withmary.compareTo(mary).- A negative number if the calling string comes before the argument —
"Mary"comes before"Michael", somary.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
- 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