Java String.compareToIgnoreCase
Order text lexicographically after applying Java’s locale-independent case rules.
A simple example
String.compareToIgnoreCase
- Start with "a" and "A"
- Do this Compare ignoring case
- Result Equal
class Main {
public static void main(String[] args) throws Exception {
System.out.println("a".compareToIgnoreCase("A") == 0);
}
}
true
Syntax
public int compareToIgnoreCase(String str)
JDK 21 method signatures (1)
public int compareToIgnoreCase(String str)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSort campus codes regardless of capitalization
A campus directory should group and order campus codes consistently across keyboard capitalization. Compare the codes under the chosen case policy and check how that policy treats an otherwise equal pair.
class Main {
public static void main(String[] args) throws Exception {
System.out.println("bio".compareToIgnoreCase("CHEM") < 0);
}
}
true
The initial b sorts before c.
Treat two status labels as tied
A directory orders short labels entered using different capitalization. Decide when two entries should compare as a tie and when the comparison should place one label first.
class Main {
public static void main(String[] args) throws Exception {
System.out.println("Paid".compareToIgnoreCase("PAID"));
}
}
0
Zero means neither label precedes the other under this comparison.
Sort art studio lockers
A school uses two-letter locker prefixes. The catalog compares the two ASCII codes in text order. Which code sorts first?
What to watch for
For names in a particular language, choose a Collator for that locale.