In Java, compareTo() compares this string with another string in dictionary order. The result is a signed int.
You pass the other string. It is required. Less than 0 means this string comes first. 0 means equal. Greater than 0 means this string comes after.
Syntax
Call compareTo on the first string. Start with this line.
java
int r = a.compareTo(b);
Call
What it does
a.compareTo(b)
Compares a with b and returns a signed int.
Only the sign of the result is reliable. The compare is case-sensitive.
Library declarations
java
public int compareTo(String anotherString);
Parameters
Parameter
Description
anotherString
Required. The string to compare with this instance.
Return Value
Return Value
Description
Less than 0
This string comes before the other.
0
The strings are equal.
Greater than 0
This string comes after the other.
Java Examples
Example 1 — Basic Lexicographic Order
See negative and positive results when strings differ.
java
public class CompareToBasic {
public static void main(String[] args) {
int r1 = "apple".compareTo("banana");
int r2 = "zebra".compareTo("apple");
System.out.println("apple vs banana: " + r1);
System.out.println("zebra vs apple: " + r2);
}
}
Output
apple vs banana: -1
zebra vs apple: 25
How It Works
First call."apple" is before "banana" → negative.
Second call."zebra" is after "apple" → positive.
Exact ints vary. Your JDK may print different magnitudes; the sign is what matters.
Dictionary order. Comparison walks characters left to right.
Example 2 — Equal Content Returns Zero
When every character matches, compareTo returns 0 (same idea as equals being true).
java
public class CompareToEqual {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
int r = a.compareTo(b);
System.out.println("compareTo = " + r);
System.out.println("equals = " + a.equals(b));
}
}
Output
compareTo = 0
equals = true
How It Works
Same letters. Both strings are "Java".
compareTo returns 0. No ordering difference.
equals is true. For String, zero from compareTo means equal content.
Still prefer equals for checks. Equality intent reads clearer with equals.
Example 3 — Put Two Names in Order
Use the sign to print the earlier name first.
java
public class CompareToSort {
public static void main(String[] args) {
String first = "Sam";
String second = "Alex";
if (first.compareTo(second) < 0) {
System.out.println(first + ", " + second);
} else {
System.out.println(second + ", " + first);
}
}
}
Output
Alex, Sam
How It Works
Compare Sam to Alex.'S' comes after 'A'.
Result is positive. So the if fails.
Else branch prints. Alex is listed before Sam.
Same idea as sorting. Larger sorts use this rule many times.
Frequently Asked Questions
compareTo() compares two strings lexicographically and returns a signed int.
anotherString is required.
Less than 0 means this comes first. 0 means equal. Greater than 0 means this comes after.
Yes.
For yes/no equality, use equals(). Use compareTo() when you need ordering.