Skip Top Navigation Bar

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

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.

int compareToIgnoreCase(String anotherString)

This method is similar to the compareTo method, but doesn't distinguish between uppercase and lowercase letters.

This method returns

Your Turn

Let's try it in the Java Playground.

boolean endsWith(String suffix)

This method returns

Your Turn

Let's try it in the Java Playground.

Complete List of String Learn Tutorials

Resources

Next Learn Tutorial