Interfaces are no longer tested on the AP CS A Exam. The compareTo method of String is still featured on the AP CS A Exam.

How String objects are compared

The String method compareTo compares String objects lexicographically, (alphabetically). All uppercase letters come before (are less than) all lowercase letters. More precisely, the compareTo method compares String objects based on the Unicode values of their characters. See the String compareTo Java API documentation for details.

The compareTo method returns one of 3 things:

String comparison examples

"Brandon" comes before (is less than) "brandon" so
"Brandon".compareTo("brandon") < 0 evaluates to true.

"Evan" comes after (is greater than) "Brandon" so
"Evan".compareTo("Brandon") < 0 evaluates to false.

Writing statements with compareTo

The return value of compareTo should always be compared against 0. Comparing the return value of compareTo against another constant (such as -1 or 1) is a mistake.

To write compareTo statements easily, pretend that the comparison operator is being written in place of the call to compareTo.

In the examples below, assume String str1 and String str2 have been declared and initialized.

Example

The boolean expression below makes logical sense but is syntactically incorrect. String objects cannot be compared using >=.

str1 >= str2

The syntactically correct expression using compareTo is:

str1.compareTo(str2) >= 0

The expression evalutes to true if str1 comes after or is the same as (is greater than or equal to) str2; otherwise, the expression evaluates to false.

Example using compareTo instead of equals

The equals method is typically used to compare String objects for equality.

str1.equals(str2)

The expression above evaluates to true if str1 and str2 represent the same value; otherwise, the expression evaluates to false.

The compareTo method can also be used to check for equality of String objects.

str1.compareTo(str2) == 0

The expression above evalutes exactly the same as the expression using the equals method.

Reading statements with compareTo

It is unlikely that AP CS A Exam multiple choice questions will misuse compareTo, so the comparison is likely to be against 0. Pretend that the comparison operator replaces the method call.

In the examples below, assume String str1 and String str2 have been declared and initialized.

Example 1

The expression
str1.compareTo(str2) < 0

means
str1 < str2

Example 2

The expression
str1.compareTo(str2) >= 0

means str1 >= str2

Additional examples

Practice compareTo with AP CS Tutor Brandon Horn.

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on compareTo on the AP CS A Exam