Library contents

Java String.compareToIgnoreCase

Order text lexicographically after applying Java’s locale-independent case rules.

A simple example

String.compareToIgnoreCase

  1. Start with "a" and "A"
  2. Do this Compare ignoring case
  3. Result Equal
After case is ignored the two ASCII letters represent the same text.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("a".compareToIgnoreCase("A") == 0);
    }
}
Output
true

Syntax

Java 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.java

Sort 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.

Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("bio".compareToIgnoreCase("CHEM") < 0);
    }
}
Output
true

The initial b sorts before c.

Advertisements

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.

Result0
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("Paid".compareToIgnoreCase("PAID"));
    }
}
Output
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?

Given'AR' · 'AT'
Worked resultAR

What to watch for

For names in a particular language, choose a Collator for that locale.

Documentation for String.compareToIgnoreCase