Java Reference Β· java.lang
Java String.compareTo() method
Reference for Java String.compareTo() and compareToIgnoreCase(): lexicographic ordering, the sign of the result, sorting and Collator for locales.
String.compareTo() compares two strings lexicographically, character by character, using the numeric UTF-16 value of each char. It returns a negative number if the receiver sorts before the argument, zero if they are equal and a positive number if it sorts after. This is the natural ordering of strings and what Collections.sort() and TreeMap use by default.
The exact magnitude of the result is an implementation detail: it is the difference of the first differing characters, or the difference of the lengths. Only its sign is meaningful.
"apple".compareTo("banana"); // negative "b".compareTo("a"); // positive "a".compareTo("a"); // 0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public int compareTo(String anotherString) public int compareToIgnoreCase(String str)
| Name | Description |
|---|---|
anotherString |
The string to compare with; must not be null. |
str |
For the ignore-case version, compared after per-character case folding. |
Returns: a negative int if this string is lexicographically less, 0 if equal, a positive int if greater.
Throws: NullPointerException if the argument is null (or the receiver).
Usage notes
- Only the sign matters. Write
a.compareTo(b) < 0, not== -1; the value can be any negative number. - Consistent with
equals().compareToreturns 0 exactly whenequals()is true, so sorted sets and maps work as expected.compareToIgnoreCaseis not consistent withequals(). - Code unit order, not dictionary order. All uppercase ASCII letters sort before lowercase ones, and accented letters come after
z. For human-friendly sorting usejava.text.Collatorwith aLocale. - Numbers inside strings sort as text:
"file10"comes before"file2". Parse the number or write a custom comparator for natural sorting. - Prefixes sort first:
"app"comes before"apple". - Comparators:
Comparator.naturalOrder(),String.CASE_INSENSITIVE_ORDERandComparator.comparing(String::length)cover most needs. - Avoid subtraction tricks with your own comparison of numbers; for numbers use
Integer.compare(). - Performance. O(n) in the length of the common prefix.
- Interface.
String implements Comparable<String>, which is whycompareTotakes aStringargument.