String Comparison

Java has three questions you can ask about two strings: are they the same object, do they contain the same text, and which comes first. Each has its own methods and traps. This page explains how equals and compareTo work, handles null, case and accents, sorts by language rules with Collator, and measures what language-aware sorting costs.

Contents

Identity, equality and ordering

Comparing strings can mean three different things:

  • Identity, a == b: are both variables the same object? This is rarely what you want, because equal text often lives in different objects. See the string pool for when it happens to be true.
  • Equality, a.equals(b): do both contain the same characters? equals first checks identity, then that the other object is a String with the same length and storage format, and then compares the bytes. HotSpot compiles that comparison into fast vector instructions.
  • Ordering, a.compareTo(b): which comes first? compareTo compares char values one by one and returns the difference at the first mismatch, or the difference in length if one string is a prefix of the other. That is fast and consistent, but it is not the order a dictionary uses.
Comparison methods
MethodSinceComparesBest for
equals, hashCodeJava 1.0Exact charactersAlmost every equality check, map keys
Objects.equals(a, b)Java 7Exact characters, null-safeValues that may be null
equalsIgnoreCaseJava 1.0Characters, ignoring case char by charKeywords, codes, headers
contentEqualsJava 1.4, 1.5A String against any CharSequenceComparing with a StringBuilder
compareTo, compareToIgnoreCaseJava 1.0, 1.2UTF-16 char valuesStable machine ordering, sorted maps
String.CASE_INSENSITIVE_ORDERJava 1.2Chars, ignoring caseCase-insensitive sorting and TreeMap keys
CollatorJava 1.1Language rulesSorting text shown to people
startsWith, endsWith, regionMatchesJava 1.0Part of a stringPrefixes, suffixes, ranges

The programs below were compiled and run on JDK 21.

== versus equals, null and hashCode

The test value is read with a Scanner, which creates a new string at run time just as reading a form field or a file does. That is the situation where == fails.

Java
import java.util.Objects;
import java.util.Scanner;

public class EqualsVsIdentity {

    public static void main(String[] args) {
        String literal = "admin";
        String typed = new Scanner("admin\n").nextLine();     // like reading user input

        System.out.println("typed == literal:      " + (typed == literal));
        System.out.println("typed.equals(literal): " + typed.equals(literal));
        System.out.println("equalsIgnoreCase:      " + "ADMIN".equalsIgnoreCase(literal));

        // Null safety
        String missing = null;
        System.out.println("\"admin\".equals(null):   " + literal.equals(missing));
        System.out.println("Objects.equals(null, null): " + Objects.equals(missing, null));
        try {
            missing.equals(literal);
        } catch (NullPointerException e) {
            System.out.println("missing.equals(...):   NullPointerException");
        }

        // equals is only true for another String; contentEquals takes any CharSequence
        StringBuilder sb = new StringBuilder("admin");
        System.out.println("equals(StringBuilder): " + literal.equals(sb));
        System.out.println("contentEquals(sb):     " + literal.contentEquals(sb));

        // Equal strings always have equal hash codes, which HashMap relies on
        System.out.println("hashCode equal:        " + (typed.hashCode() == literal.hashCode())
            + " (" + literal.hashCode() + ")");
        System.out.println("\"Aa\" and \"BB\" hash:    "
            + "Aa".hashCode() + " and " + "BB".hashCode()
            + ", equals: " + "Aa".equals("BB"));

        // switch on a String uses hashCode, then equals
        System.out.println("switch:                " + role(typed));
    }

    static String role(String name) {
        return switch (name) {
            case "admin" -> "full access";
            case "guest" -> "read only";
            default -> "unknown";
        };
    }
}

Output:

Output
typed == literal:      false
typed.equals(literal): true
equalsIgnoreCase:      true
"admin".equals(null):   false
Objects.equals(null, null): true
missing.equals(...):   NullPointerException
equals(StringBuilder): false
contentEquals(sb):     true
hashCode equal:        true (92668751)
"Aa" and "BB" hash:    2112 and 2112, equals: false
switch:                full access
  • The typed admin is a different object from the literal, so == is false while equals is true. With two literals, == would have been true, which is how this bug survives tests.
  • equals(null) returns false, but calling equals on a null reference throws. Writing the constant first, "admin".equals(input), or using Objects.equals, avoids the exception.
  • equals is false for a StringBuilder with the same text, because it requires a String. contentEquals accepts any CharSequence.
  • Equal strings always have equal hash codes, which is what HashMap relies on. The reverse is not true: Aa and BB both hash to 2112. A string's hash code is computed once and cached inside the object.
  • A switch on a string compiles to a switch on hashCode() followed by an equals check, so it is both fast and correct.

How compareTo orders strings

compareTo defines the natural order used by sort, TreeMap and TreeSet. The examples are chosen to show its results that surprise people: capitals, prefixes, numbers inside text, accents, and characters outside the BMP.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class OrderingRules {

    public static void main(String[] args) {
        // compareTo returns a difference, not just -1, 0 or 1
        System.out.println("\"apple\".compareTo(\"banana\") = " + "apple".compareTo("banana")
            + "   ('a' - 'b')");
        System.out.println("\"app\".compareTo(\"apple\")    = " + "app".compareTo("apple")
            + "   (3 - 5, a prefix sorts first)");
        System.out.println("\"Zoo\".compareTo(\"apple\")    = " + "Zoo".compareTo("apple")
            + "   ('Z' 90 - 'a' 97: all capitals before lowercase)");
        System.out.println("\"10\".compareTo(\"9\")         = " + "10".compareTo("9")
            + "   (text, not numbers)");

        // Sorting: natural order compares chars by their UTF-16 values
        List<String> files = new ArrayList<>(List.of("file10.txt", "File2.txt", "file2.txt",
            "file1.txt", "\u00E9t\u00E9.txt"));
        files.sort(Comparator.naturalOrder());
        System.out.println("natural:     " + files);
        files.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
        System.out.println("by length:   " + files);
        files.sort(OrderingRules::numberAware);
        System.out.println("numbers:     " + files);

        // nulls must be placed explicitly
        List<String> withNull = Arrays.asList("b", null, "a");
        withNull.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
        System.out.println("nullsFirst:  " + withNull);
        try {
            Arrays.asList("b", null, "a").sort(Comparator.naturalOrder());
        } catch (NullPointerException e) {
            System.out.println("natural with null: NullPointerException");
        }

        // UTF-16 order is not code point order above U+FFFF
        String fullwidthTilde = "\uFF5E";
        String clef = "\uD834\uDD1E";
        System.out.println("compareTo says U+FF5E "
            + (fullwidthTilde.compareTo(clef) < 0 ? "<" : ">")
            + " U+1D11E; by code point it is "
            + (Integer.compare(0xFF5E, clef.codePointAt(0)) < 0 ? "<" : ">"));
    }

    // Compares runs of digits by their numeric value, so file2 sorts before file10
    static int numberAware(String a, String b) {
        int i = 0;
        int j = 0;
        while (i < a.length() && j < b.length()) {
            char ca = a.charAt(i);
            char cb = b.charAt(j);
            if (Character.isDigit(ca) && Character.isDigit(cb)) {
                int si = i;
                int sj = j;
                while (i < a.length() && Character.isDigit(a.charAt(i))) {
                    i++;
                }
                while (j < b.length() && Character.isDigit(b.charAt(j))) {
                    j++;
                }
                int cmp = Long.compare(Long.parseLong(a.substring(si, i)),
                    Long.parseLong(b.substring(sj, j)));
                if (cmp != 0) {
                    return cmp;
                }
            } else {
                int cmp = Character.compare(Character.toLowerCase(ca), Character.toLowerCase(cb));
                if (cmp != 0) {
                    return cmp;
                }
                i++;
                j++;
            }
        }
        return Integer.compare(a.length() - i, b.length() - j);
    }
}

Output:

Output
"apple".compareTo("banana") = -1   ('a' - 'b')
"app".compareTo("apple")    = -2   (3 - 5, a prefix sorts first)
"Zoo".compareTo("apple")    = -7   ('Z' 90 - 'a' 97: all capitals before lowercase)
"10".compareTo("9")         = -8   (text, not numbers)
natural:     [File2.txt, file1.txt, file10.txt, file2.txt, été.txt]
by length:   [été.txt, File2.txt, file1.txt, file2.txt, file10.txt]
numbers:     [file1.txt, File2.txt, file2.txt, file10.txt, été.txt]
nullsFirst:  [null, a, b]
natural with null: NullPointerException
compareTo says U+FF5E > U+1D11E; by code point it is <
  • The result is a difference: 'a' - 'b' is -1, and for the prefix app it is the length difference 3 - 5 = -2. Only the sign is specified, so test < 0, never == -1.
  • All capitals come before all lowercase letters, because 'Z' is 90 and 'a' is 97. Accented letters such as é (233) come after z, so été.txt sorted last.
  • Digits compare as characters, so "10" sorts before "9" and file10 before file2. The numberAware comparator compares runs of digits by value, giving the order a file manager shows.
  • Comparator.comparing(String::length).thenComparing(...) sorts by a key first and breaks ties with a second comparator.
  • Natural order throws NullPointerException on a null element. Comparator.nullsFirst or nullsLast wraps a comparator to place nulls explicitly.
  • Because compareTo compares UTF-16 chars, U+FF5E sorts after U+1D11E, whose first char is the surrogate U+D834. Ordered by code point it is the other way round. This rarely matters, but it means Java's order can differ from a database that sorts by code point.

For writing comparators in general, see Comparable and Comparator.

Ignoring case

Case-insensitive comparison looks simple, but it has its own ordering rules and depends on how characters map between cases. The names include the same name in two cases, and the last checks use German and Turkish letters.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.TreeMap;

public class CaseInsensitive {

    public static void main(String[] args) {
        System.out.println("\"Zoo\".compareToIgnoreCase(\"apple\") = "
            + "Zoo".compareToIgnoreCase("apple"));

        List<String> names = new ArrayList<>(List.of("bob", "Alice", "alice", "Bob", "carol"));
        names.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println("CASE_INSENSITIVE_ORDER:  " + names);
        names.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.naturalOrder()));
        System.out.println("then natural, stable:    " + names);

        // A case-insensitive map: one key per name regardless of case
        TreeMap<String, Integer> counts = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        for (String n : names) {
            counts.merge(n, 1, Integer::sum);
        }
        System.out.println("case-insensitive TreeMap: " + counts);
        Set<String> tree = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        tree.addAll(names);
        Set<String> hash = new HashSet<>(names);
        System.out.println("contains(\"ALICE\"): TreeSet " + tree.contains("ALICE")
            + ", HashSet " + hash.contains("ALICE")
            + "; sizes " + tree.size() + " and " + hash.size());

        // equalsIgnoreCase compares char by char
        System.out.println("\"STRASSE\".equalsIgnoreCase(\"stra\u00DFe\") = "
            + "STRASSE".equalsIgnoreCase("stra\u00DFe"));
        System.out.println("\"\u00C9COLE\".equalsIgnoreCase(\"\u00E9cole\")   = "
            + "\u00C9COLE".equalsIgnoreCase("\u00E9cole"));

        // Lowercasing with the default locale: the Turkish i problem
        Locale tr = Locale.forLanguageTag("tr");
        String title = "TITLE";
        System.out.println("Turkish lower: " + title.toLowerCase(tr) + ", equals \"title\": "
            + title.toLowerCase(tr).equals("title"));
        System.out.println("ROOT lower:    " + title.toLowerCase(Locale.ROOT));
        System.out.println("equalsIgnoreCase is not affected by locale: "
            + title.equalsIgnoreCase("title"));
    }
}

Output:

Output
"Zoo".compareToIgnoreCase("apple") = 25
CASE_INSENSITIVE_ORDER:  [Alice, alice, bob, Bob, carol]
then natural, stable:    [Alice, alice, Bob, bob, carol]
case-insensitive TreeMap: {Alice=2, Bob=2, carol=1}
contains("ALICE"): TreeSet true, HashSet false; sizes 3 and 5
"STRASSE".equalsIgnoreCase("straße") = false
"ÉCOLE".equalsIgnoreCase("école")   = true
Turkish lower: tıtle, equals "title": false
ROOT lower:    title
equalsIgnoreCase is not affected by locale: true
  • compareToIgnoreCase("Zoo", "apple") is 25, so Zoo now sorts after apple.
  • CASE_INSENSITIVE_ORDER treats Alice and alice as equal, so their order after sorting depends on the input order (the sort is stable). Adding thenComparing(naturalOrder()) makes the result fully determined.
  • A TreeMap with CASE_INSENSITIVE_ORDER keeps one key per name whatever its case, counting Alice and Bob twice each. It keeps the first spelling it saw as the key.
  • Such a comparator is inconsistent with equals: a TreeSet using it holds 3 names and finds ALICE, while a HashSet of the same input, which uses equals, holds 5 and does not. Mixing the two kinds of set for the same data gives contradictory answers.
  • equalsIgnoreCase compares one char at a time, converting each to upper and then lower case. That handles É and é, but not ß against SS, which needs two characters.
  • Lowercasing with a Turkish locale turns I into dotless ı, so "TITLE".toLowerCase(tr).equals("title") is false. equalsIgnoreCase does not use a locale and is not affected. When you do convert case for comparison, use Locale.ROOT.

Language-aware order with Collator

People expect Éva next to Eva, not after zack. A Collator implements the sorting rules of a language. The names mix case and accents so that all three comparison strengths behave differently.

Java
import java.text.CollationKey;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

public class CollatorDemo {

    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("\u00E9mile", "Zo\u00EB", "adam", "\u00C9va",
            "zack", "Eva", "eva"));

        names.sort(Comparator.naturalOrder());
        System.out.println("compareTo order:   " + names);
        names.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println("case-insensitive:  " + names);
        Collator french = Collator.getInstance(Locale.FRENCH);
        names.sort(french);
        System.out.println("Collator (French): " + names);

        // Strength: which differences count
        for (int strength : new int[] {Collator.PRIMARY, Collator.SECONDARY, Collator.TERTIARY}) {
            Collator c = Collator.getInstance(Locale.FRENCH);
            c.setStrength(strength);
            System.out.printf("%-9s Eva=eva? %-5b Eva=\u00C9va? %b%n",
                strength == 0 ? "PRIMARY" : strength == 1 ? "SECONDARY" : "TERTIARY",
                c.compare("Eva", "eva") == 0, c.compare("Eva", "\u00C9va") == 0);
        }

        // Language rules differ: Swedish sorts \u00E4 after z, German next to a
        List<String> words = List.of("\u00E4pple", "apple", "zebra");
        List<String> sv = new ArrayList<>(words);
        sv.sort(Collator.getInstance(Locale.forLanguageTag("sv")));
        List<String> de = new ArrayList<>(words);
        de.sort(Collator.getInstance(Locale.GERMAN));
        System.out.println("Swedish: " + sv + "   German: " + de);

        // CollationKey: compute once per string, then compare cheaply
        Collator c = Collator.getInstance(Locale.FRENCH);
        CollationKey[] keys = names.stream().map(c::getCollationKey).toArray(CollationKey[]::new);
        Arrays.sort(keys);
        System.out.println("sorted by CollationKey: "
            + Arrays.stream(keys).map(CollationKey::getSourceString).toList());
    }
}

Output:

Output
compareTo order:   [Eva, Zoë, adam, eva, zack, Éva, émile]
case-insensitive:  [adam, Eva, eva, zack, Zoë, émile, Éva]
Collator (French): [adam, émile, eva, Eva, Éva, zack, Zoë]
PRIMARY   Eva=eva? true  Eva=Éva? true
SECONDARY Eva=eva? true  Eva=Éva? false
TERTIARY  Eva=eva? false Eva=Éva? false
Swedish: [apple, zebra, äpple]   German: [apple, äpple, zebra]
sorted by CollationKey: [adam, émile, eva, Eva, Éva, zack, Zoë]
  • compareTo put capitals first and accented names last. Case-insensitive order fixed the capitals but still put émile and Éva after Zoë. The French collator gave dictionary order, with accented letters next to their base letters.
  • The strength decides which differences count. PRIMARY compares only base letters, so Eva, eva and Éva are all equal. SECONDARY also counts accents, and TERTIARY, the default, also counts case.
  • Rules depend on the language: Swedish treats ä as a separate letter after z, while German sorts it with a. Use the locale of the people reading the list.
  • A CollationKey converts a string once into a form that compares quickly, which pays off when the same strings are compared many times, as in a sort.

Collator is not thread-safe; create one per thread or per use. For more complete language support, ICU4J's Collator follows the latest Unicode rules.

Prefixes, suffixes and blank checks

Many comparisons only look at part of a string. A file name with an uppercase extension shows where the simple checks are case-sensitive.

Java
import java.util.Locale;

public class OtherChecks {

    public static void main(String[] args) {
        String file = "Report_2026.PDF";

        System.out.println("startsWith(\"Report\"):    " + file.startsWith("Report"));
        System.out.println("startsWith(\"2026\", 7):   " + file.startsWith("2026", 7));
        System.out.println("endsWith(\".pdf\"):        " + file.endsWith(".pdf"));
        System.out.println("lower endsWith(\".pdf\"):  "
            + file.toLowerCase(Locale.ROOT).endsWith(".pdf"));
        System.out.println("endsWithIgnoreCase:      " + endsWithIgnoreCase(file, ".pdf"));
        System.out.println("contains(\"2026\"):        " + file.contains("2026"));
        System.out.println("regionMatches(true, ...): "
            + file.regionMatches(true, 7, "2026.pdf", 0, 8));
        System.out.println("matches(\".*\\\\d{4}.*\"):   " + file.matches(".*\\d{4}.*"));

        // isEmpty vs isBlank
        for (String s : new String[] {"", "  ", " x "}) {
            System.out.printf("[%s] isEmpty=%b isBlank=%b%n", s, s.isEmpty(), s.isBlank());
        }
    }

    // No copy of the string is made
    static boolean endsWithIgnoreCase(String s, String suffix) {
        int start = s.length() - suffix.length();
        return start >= 0 && s.regionMatches(true, start, suffix, 0, suffix.length());
    }
}

Output:

Output
startsWith("Report"):    true
startsWith("2026", 7):   true
endsWith(".pdf"):        false
lower endsWith(".pdf"):  true
endsWithIgnoreCase:      true
contains("2026"):        true
regionMatches(true, ...): true
matches(".*\\d{4}.*"):   true
[] isEmpty=true isBlank=true
[  ] isEmpty=false isBlank=true
[ x ] isEmpty=false isBlank=false
  • startsWith has an overload with an offset, so startsWith("2026", 7) checks the text at index 7.
  • endsWith(".pdf") is false for .PDF. Lowercasing the whole name works but copies it. regionMatches(true, ...) compares a range ignoring case without copying, which the endsWithIgnoreCase helper uses.
  • isEmpty() is true only for length 0, while isBlank() (Java 11) is also true for whitespace-only strings. Both throw on null. See removing whitespace for what counts as whitespace.

What language-aware sorting costs

The program sorts 200,000 random eight-letter names, some with accented letters, using each kind of comparison. Each timing is the best of 3 runs on a fresh copy of the input.

Java
import java.text.CollationKey;
import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
import java.util.Random;

public class CompareSpeed {

    public static void main(String[] args) {
        Random random = new Random(11);
        String[] names = new String[200000];
        String letters = "abcdefghijklmnopqrstuvwxyz\u00E9\u00E8\u00FC";
        for (int i = 0; i < names.length; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append(Character.toUpperCase(letters.charAt(random.nextInt(26))));
            for (int k = 0; k < 7; k++) {
                sb.append(letters.charAt(random.nextInt(letters.length())));
            }
            names[i] = sb.toString();
        }
        System.out.printf("sort %,d names of 8 letters%n", names.length);
        Collator collator = Collator.getInstance(Locale.FRENCH);

        time("natural (compareTo)", names, a -> Arrays.sort(a, Comparator.naturalOrder()));
        time("CASE_INSENSITIVE_ORDER", names, a -> Arrays.sort(a, String.CASE_INSENSITIVE_ORDER));
        time("Collator.compare", names, a -> Arrays.sort(a, collator));
        time("CollationKey", names, a -> {
            CollationKey[] keys = new CollationKey[a.length];
            for (int i = 0; i < a.length; i++) {
                keys[i] = collator.getCollationKey(a[i]);
            }
            Arrays.sort(keys);
        });
    }

    interface Sorter {
        void sort(String[] a);
    }

    // Best of 3 runs, each on a fresh copy of the unsorted input
    static void time(String name, String[] input, Sorter sorter) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            String[] copy = input.clone();
            long t0 = System.nanoTime();
            sorter.sort(copy);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-24s %7.1f ms%n", name, best / 1e6);
    }
}

Output (measured roughly on JDK 21, 2-CPU Linux):

Output
sort 200,000 names of 8 letters
natural (compareTo)         87.2 ms
CASE_INSENSITIVE_ORDER      90.8 ms
Collator.compare          2536.5 ms
CollationKey               443.0 ms
  • Natural order and CASE_INSENSITIVE_ORDER took about the same time.
  • Collator.compare was more than twenty times slower. A sort makes millions of comparisons, and each one runs the full language rules on both strings.
  • Building a CollationKey for each name once and sorting the keys was about six times faster than using the collator directly, while still slower than natural order.

For lists shown to people, collation is worth its cost. For keys, indexes and anything a program reads, use natural order, which is fast and does not change with the locale.

Which comparison to use

Choosing a string comparison
QuestionUse
Same text?a.equals(b)
Same text, either may be null?Objects.equals(a, b) or "CONSTANT".equals(input)
Same text, ignoring case?a.equalsIgnoreCase(b)
Same text as a StringBuilder?s.contentEquals(sb)
Same object?a == b, almost never needed
Order for code, maps and filescompareTo / Comparator.naturalOrder()
Order ignoring caseString.CASE_INSENSITIVE_ORDER, then natural order for ties
Order for peopleCollator.getInstance(locale), with CollationKey for big sorts
Numbers inside namesA number-aware comparator
Same text with different accents encodingNormalize first; see characters and normalization