Java String compareToIgnoreCase() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The compareToIgnoreCase() method compares two strings in dictionary order while ignoring letter case. It returns the same style of int as compareTo(), but treats A and a as equivalent for sorting and ordering.

01

Ignore Case

A equals a for order.

02

Returns int

Negative, zero, positive.

03

Lexicographic

Dictionary-style order.

04

vs compareTo()

Case on vs case off.

05

Sorting

Usernames, tags, names.

06

vs equalsIgnoreCase()

Order vs true/false.

Definition and Usage

In Java, compareToIgnoreCase(String str) is a member of java.lang.String. It walks both strings in parallel, comparing characters after normalizing case, and returns whether the caller would appear before, at, or after the argument in a case-insensitive sorted list.

When two strings differ only in capitalization—such as "Hello, World!" and "HELLO, world!"—the method returns 0, even though equals() would return false.

💡
Beginner Tip

Need a yes/no “are these the same ignoring case?” check? Use equalsIgnoreCase(). Need to sort or decide which string comes first? Use compareToIgnoreCase().

📝 Syntax

The compareToIgnoreCase() method is declared in the String class:

java
public int compareToIgnoreCase(String str)

Parameters

  • str — the string to compare against. Must not be null (throws NullPointerException).

Return Value

  • Negative — caller is lexicographically less than str, ignoring case.
  • Zero — strings are equal ignoring case.
  • Positive — caller is lexicographically greater than str, ignoring case.

⚡ Quick Reference

ExpressionResultNotes
"Hello".compareToIgnoreCase("HELLO")0Equal ignoring case
"apple".compareToIgnoreCase("Banana")Negativeapple before Banana
"Apple".compareTo("apple")NegativeCase-sensitive compareTo
"Apple".compareToIgnoreCase("apple")0Case ignored
"Java".equalsIgnoreCase("JAVA")trueBoolean equality check
Equal ignoring case
s1.compareToIgnoreCase(s2) == 0

Same when case ignored

Sort list
list.sort(String::compareToIgnoreCase)

Case-insensitive order

Avoid manual
// skip toLowerCase() on both

Built-in normalization

Check sign
result < 0, == 0, > 0

Same as compareTo()

Examples Gallery

Run these in Java 8+. They show equal strings with different case, comparison with compareTo(), sorting, and the difference from equalsIgnoreCase().

📚 Getting Started

Compare two greetings that differ only in capitalization.

Example 1 — Strings Equal Ignoring Case

"Hello, World!" and "HELLO, world!" contain the same letters in the same order—only case differs.

java
public class StringComparison {
    public static void main(String[] args) {
        String str1 = "Hello, World!";
        String str2 = "HELLO, world!";

        int result = str1.compareToIgnoreCase(str2);

        if (result == 0) {
            System.out.println("The strings are equal (ignoring case).");
        } else if (result < 0) {
            System.out.println("str1 is before str2.");
        } else {
            System.out.println("str1 is after str2.");
        }
        System.out.println("compareToIgnoreCase returned: " + result);
    }
}

How It Works

Each character pair matches when case is ignored, so the method returns 0. Note that str1.equals(str2) would still be false because the exact characters differ.

Example 2 — compareTo() vs compareToIgnoreCase()

See how case-sensitive and case-insensitive comparison diverge on the same pair of strings.

java
public class CompareBothMethods {
    public static void main(String[] args) {
        String a = "Apple";
        String b = "apple";

        System.out.println("compareTo():            " + a.compareTo(b));
        System.out.println("compareToIgnoreCase():  " + a.compareToIgnoreCase(b));
    }
}

How It Works

compareTo() sees 'A' (65) vs 'a' (97) and returns negative. compareToIgnoreCase() treats them as the same letter and continues until both strings are fully matched, returning 0.

📈 Practical Patterns

Sorting, different words, and choosing the right comparison method.

Example 3 — Sort Usernames Ignoring Case

Build a case-insensitive sorted list without calling toLowerCase() on every element yourself.

java
import java.util.Arrays;
import java.util.List;

public class SortIgnoreCase {
    public static void main(String[] args) {
        List<String> tags = Arrays.asList("java", "Python", "C++", "android");

        tags.sort(String::compareToIgnoreCase);

        System.out.println(tags);
    }
}

How It Works

String::compareToIgnoreCase is a method reference passed to sort. Python and java order by letter value after case normalization, so uppercase/lowercase spelling does not push words to unexpected positions.

Example 4 — Different Words Still Order Normally

Ignoring case does not make different strings equal—Java still comes before Python.

java
public class DifferentWords {
    public static void main(String[] args) {
        String lang1 = "JAVA";
        String lang2 = "Python";

        int result = lang1.compareToIgnoreCase(lang2);

        System.out.println("Result: " + result);
        System.out.println(result < 0 ? "JAVA before Python" : "JAVA after Python");
    }
}

How It Works

The first characters differ: 'J' vs 'P'. Case is irrelevant here because the letters themselves are different. The method returns a negative value because JAVA belongs earlier in the alphabet.

Example 5 — compareToIgnoreCase() vs equalsIgnoreCase()

Pick the method that matches your question: ordering or equality.

java
public class CompareVsEquals {
    public static void main(String[] args) {
        String input = "admin";
        String stored = "ADMIN";

        boolean same = input.equalsIgnoreCase(stored);
        int order  = input.compareToIgnoreCase(stored);

        System.out.println("equalsIgnoreCase: " + same);
        System.out.println("compareToIgnoreCase: " + order);
        System.out.println("equals (case-sensitive): " + input.equals(stored));
    }
}

How It Works

For login-style matching, equalsIgnoreCase reads naturally. For sorting a list where admin and ADMIN should occupy the same rank, compareToIgnoreCase == 0 tells you they tie. Neither replaces equals() when exact character match is required.

🚀 Common Use Cases

  • Sorting names or tags — display lists where apple and Apple should not split apart because of case.
  • Search ranking — order results without penalizing capitalization differences.
  • Ordered sets/maps — custom comparators built on case-insensitive string order.
  • File or path comparison — on case-insensitive file systems (conceptually similar behavior).
  • Avoiding manual toLowerCase() — let Java handle case normalization inside one readable call.

🧠 How compareToIgnoreCase() Works

1

Walk both strings

Java reads character by character from the caller and the argument.

Scan
2

Compare ignoring case

Each pair is compared after Unicode case folding rules used by Character.toUpperCase / toLowerCase logic.

Normalize
3

First difference or length

If characters differ (after case ignore), return the difference. If one string is a prefix, shorter wins.

Decide
=

int result

Negative, zero, or positive—case-insensitive sort order.

📝 Notes

  • Comparison still uses Unicode character values after case normalization—not locale-specific human collation rules.
  • Passing null throws NullPointerException.
  • compareToIgnoreCase() == 0 does not imply equals() is true—only case-insensitive lexical equality.
  • For simple “same text ignoring case?” checks, equalsIgnoreCase() is clearer than testing for zero.
  • Locale-sensitive sorting (e.g. Turkish I / ı) may need Collator instead of this method.

⚡ Optimization

compareToIgnoreCase() is the standard optimized approach for case-insensitive lexicographic comparison. It avoids allocating two new lowercased strings via toLowerCase() on every compare during a sort. For large sorts, prefer this method or a Comparator based on it rather than converting strings manually in a loop.

Conclusion

The compareToIgnoreCase() method is Java’s built-in answer to “which string comes first if we ignore capitalization?” It pairs naturally with compareTo() and saves you from fragile manual case conversion.

Use it for ordering and sorting; use equalsIgnoreCase() for boolean sameness checks; use compareTo() when case must affect order. Together they cover the comparison tasks beginners meet most often.

💡 Best Practices

✅ Do

  • Use for case-insensitive sorting with list.sort(String::compareToIgnoreCase)
  • Check the sign (< 0, == 0, > 0), not exact -1/0/1
  • Use equalsIgnoreCase() for login or password-style matching
  • Guard against null before comparing
  • Learn compareTo() first, then add ignore-case when needed

❌ Don’t

  • Assume return 0 means equals() is true
  • Use for locale-specific alphabetical order in every language
  • Call toLowerCase() on both strings when this method suffices
  • Confuse with == (reference comparison)
  • Use for numeric string ordering ("10" vs "2")

Key Takeaways

Knowledge Unlocked

Five things to remember about compareToIgnoreCase()

Use these points when comparing strings without caring about case.

5
Core concepts
🔢 02

Returns int

Same sign rules.

Return
📚 03

vs compareTo()

Case on vs off.

Compare
📈 04

Sorting

Tags, names, lists.

Use case
05

Not equals()

Order, not identity.

Edge case

❓ Frequently Asked Questions

compareToIgnoreCase(String str) compares two strings lexicographically while ignoring case differences. It returns a negative int if the caller sorts before the argument, zero if they match ignoring case, or a positive int if the caller sorts after.
Call it on a String: string1.compareToIgnoreCase(string2). It takes one String argument and returns an int, using the same sign convention as compareTo().
compareTo() is case-sensitive—"Apple" and "apple" compare as different. compareToIgnoreCase() treats uppercase and lowercase forms of the same letter as equal for ordering purposes.
No. equalsIgnoreCase() returns boolean true/false for equality. compareToIgnoreCase() returns an int for ordering (before, equal, after). Use equalsIgnoreCase() to test sameness; use compareToIgnoreCase() for sorting.
Not necessarily. compareToIgnoreCase() == 0 means the strings are equal ignoring case, but "Hello" and "HELLO" still return false from equals() because the exact characters differ.
Use it when sorting or ordering strings where case should not affect position—usernames, tags, file extensions, or search results—without manually calling toLowerCase() on both strings first.

Master Java String Comparison

Pair compareToIgnoreCase() with compareTo() so you can choose case-sensitive or case-insensitive ordering in any project.

Next: concat() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful