Comparing Two String Objects Using compareTo Methods
String Methods
We've compiled some helpful String methods below.
 |
Methods that are part of the AP Computer Science A Java subset are denoted by the APCSA label. |
A complete list of String methods can be found in the String API.
int compareTo(String anotherString)
This method returns
- 0 if this
String has the same value as anotherString.
- a value less than 0 if this
String is lexicographically less than anotherString. Lexicographically is also referred to as dictionary order. It is the way we alphabetize words. In computers each character is assigned a number based on the ASCII codes. In this system, uppercase letters have a lower value than uppercase letters. In other words, uppercase letters come before lowercase letters in alphabetical order. For example, "apple" is lexicographically before "axel", since "p" comes before "x".
- a value greater than 0 if this
String is lexicographically greater than anotherString.
It is helpful to think of lexicographical order a little like alphabetical order, but uppercase letters come before lowercase letters. Look at the two strings that are being compared, draw a < above the compareTo method if the first word comes before the second word and a > if the first word comes after the second. If it is less than, the return value is negative. If it is greater than, the return value is positive. This visualization helps to illustrate this process.
Your Turn
Let's try it in the Java Playground.
- Add a
String with the same value as name and compare the two.
value is assigned a value greater than 0, since D comes after A.
value2 is assigned a value less than 0, since A comes before D.
int compareToIgnoreCase(String anotherString)
This method is similar to the compareTo method, but doesn't distinguish between uppercase and lowercase letters.
This method returns
- 0 if this
String has the same value as anotherString.
- a value less than 0 if this
String is lexicographically less than anotherString, while ignoring the difference between upper and lowercase letters.
- a value greater than 0 if this
String is lexicographically greater than anotherString, while ignoring the difference between upper and lowercase letters.
Your Turn
Let's try it in the Java Playground.
- Predict the value of
value.
- Run the code to determine whether your prediction is correct.
boolean endsWith(String suffix)
This method returns
true if this String ends with suffix and false otherwise.
Your Turn
Let's try it in the Java Playground.
- Predict the values of
value and value2.
- Run the code to determine whether your predictions are correct.
value is assigned true since Awesomeness ends with ness.
value2 is assigned false. While Awesomeness contains some, it doesn't end with some.
Complete List of String Learn Tutorials
Resources
Next Learn Tutorial