Library contents

Java String.compareTo

Compare strings lexicographically and use the sign of the result to order them.

A simple example

String.compareTo

  1. Start with "a" and "b"
  2. Do this Compare their order
  3. Result a comes first
The first characters already differ. The code for a is smaller than the code for b.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("a".compareTo("b") < 0);
    }
}
Output
true

Syntax

Java 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.java

Order 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.

Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("A-12".compareTo("B-01") < 0);
    }
}
Output
true

The first different character places shelf A before shelf B.

Advertisements

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.

Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("10".compareTo("2") < 0);
    }
}
Output
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?

Given'AR' · 'AT'
Worked resultAR

What to watch for

The numeric difference need not equal one. This ordering is based on UTF-16 units, not a locale-specific dictionary.

Documentation for String.compareTo