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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.compareTo(other)

Parameters

ParameterDescription
other
String
The string to compare with.

Return value

An int.

Examples

Alphabetical order
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.

Sort ignoring case
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

VersionChange
Java Java 1.0Added

Was this page helpful?