Java String.compareTo
Compare strings lexicographically and use the sign of the result to order them.
A simple example
String.compareTo
- Start with "a" and "b"
- Do this Compare their order
- Result a comes first
class Main {
public static void main(String[] args) throws Exception {
System.out.println("a".compareTo("b") < 0);
}
}
true
Syntax
public int compareTo(String anotherString)
JDK 21 method signatures (1)
public int compareTo(String anotherString)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaOrder two shelf labels
A shelf directory arranges two printed labels in text order. Inspect the sign of the comparison so the sorting code can distinguish a tie from the label that belongs first.
class Main {
public static void main(String[] args) throws Exception {
System.out.println("A-12".compareTo("B-01") < 0);
}
}
true
The first different character places shelf A before shelf B.
Spot text sorting in a room directory
A directory orders shelf or room labels as text. Compare their spelling under the chosen ordering rule and check what happens when a label contains digits that look like a number.
class Main {
public static void main(String[] args) throws Exception {
System.out.println("10".compareTo("2") < 0);
}
}
true
The first digit 1 sorts before 2. Parse numbers when numeric ordering is required.
Sort art studio lockers
A school uses two-letter locker prefixes. The catalog compares the two ASCII codes in text order. Which code sorts first?
What to watch for
The numeric difference need not equal one. This ordering is based on UTF-16 units, not a locale-specific dictionary.