Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.compareTo()

Compares two strings in dictionary (lexicographic) order.

Available since: Java 1.0

Syntax

public int compareTo(String anotherString)

Parameters

ParameterTypeDescription
anotherStringStringThe string to compare this one with.

Return value

intA negative number if this string comes first, 0 if they are equal, a positive number if it comes later.

Examples

The sign of the result shows the order:

void main() {
    IO.println("apple".compareTo("banana"));
    IO.println("pear".compareTo("pear"));
    IO.println("pear".compareTo("Pear"));
}

Output:

-1
0
32

Check the sign, not the exact number:

void main() {
    String a = "Oleg";
    String b = "Anna";
    if (a.compareTo(b) > 0) {
        IO.println(b + " comes first");
    }
}

Output:

Anna comes first

Notes

Character codes are compared, so all uppercase letters come before lowercase ones: "Zoo" is less than "apple". Use compareToIgnoreCase() to ignore case, and java.text.Collator for the rules of a specific language.

See also

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.