CKTIS / Java
String.compareTo — lexicographic comparison
String.compareTo compares strings lexicographically. The result's sign determines order; zero means equal contents.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public int compareTo(String anotherString)
// Usage: int result = left.compareTo(right);String.compareTo returns an int: a negative result means the left string precedes the right; positive means it follows. Zero corresponds to equality according to equals.
Comparison is case-sensitive and uses UTF-16 code-unit (char) values, not linguistic rules. The result is the difference between the first differing units; if one string prefixes the other, it is the length difference. Do not assume only -1, 0, or 1: test the sign.
A null argument causes NullPointerException. Use Collator for locale-sensitive comparisons.
Examples
public class Main {
public static void main(String[] args) {
System.out.println("cat".compareTo("car"));
System.out.println("car".compareTo("cart"));
System.out.println("cat".compareTo("cat"));
System.out.println("A".compareTo("a") < 0);
}
}Result
2 -1 0 true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.