Java 25 (LTS) reference · String Methods
Java String compareTo() Method
Compare two strings alphabetically: negative if this comes first, 0 if equal, positive if it comes after.
Java 25 (LTS) Since Java 1.0
Syntax
string.compareTo(other)
Parameters
| Parameter | Description |
|---|---|
otherString |
The string to compare with. |
Return value
An int.
Examples
public class Main {
public static void main(String[] args) {
System.out.println("apple".compareTo("banana") < 0);
System.out.println("pear".compareTo("pear"));
System.out.println("Zebra".compareTo("apple") < 0); // upper case sorts before lower case
}
}
Output
true 0 true
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("cleo", "Ana", "ben"));
names.sort(String::compareToIgnoreCase);
System.out.println(names);
}
}
Output
[Ana, ben, cleo]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
string.equals()· Compare the contents of two strings. Never use == for strings: it compares object identity, not text.list.sort()· Sort a list in place with a Comparator, or by natural order when you pass null. Collections.sort() does the same.- Java Strings · tutorial