String.compareTo()
Compares two strings in dictionary (lexicographic) order.
Available since: Java 1.0
Syntax
public int compareTo(String anotherString)Parameters
| Parameter | Type | Description |
|---|---|---|
| anotherString | String | The 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
32Check 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 firstNotes
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
- String.equals() — Compares the contents of two strings.
- Comparable.compareTo() — Defines the natural order of a class — used by sort() and TreeSet.
- Comparator.comparing() — Creates a comparator that compares objects by one key.
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.