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,
: are both variables the same object? This is rarely what you want, because equal text often lives in different objects. Seea == bthe string pool for when it happens to be true. - Equality,
: do both contain the same characters?a.equals(b) first checks identity, then that the other object is aequals with the same length and storage format, and then compares the bytes. HotSpot compiles that comparison into fast vector instructions.String - Ordering,
: which comes first?a.compareTo(b) 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.compareTo
| Method | Since | Compares | Best for |
|---|---|---|---|
equalshashCode | Java 1.0 | Exact characters | Almost every equality check, map keys |
Objects.equals(a, b) | Java 7 | Exact characters, null-safe | Values that may be null |
equalsIgnoreCase | Java 1.0 | Characters, ignoring case char by char | Keywords, codes, headers |
contentEquals | Java 1.4, 1.5 | A StringCharSequence | Comparing with a StringBuilder |
compareTocompareToIgnoreCase | Java 1.0, 1.2 | UTF-16 char values | Stable machine ordering, sorted maps |
String.CASE_INSENSITIVE_ORDER | Java 1.2 | Chars, ignoring case | Case-insensitive sorting and TreeMap |
Collator | Java 1.1 | Language rules | Sorting text shown to people |
startsWithendsWithregionMatches | Java 1.0 | Part of a string | Prefixes, 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==
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:
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
is a different object from the literal, soadmin is false while== is true. With two literals,equals would have been true, which is how this bug survives tests.== returns false, but callingequals(null) on a null reference throws. Writing the constant first,equals , or using"admin".equals(input) , avoids the exception.Objects.equals is false for aequals with the same text, because it requires aStringBuilder .String accepts anycontentEquals .CharSequence- Equal strings always have equal hash codes, which is what
relies on. The reverse is not true:HashMap andAa both hash to 2112. A string's hash code is computed once and cached inside the object.BB - A
on a string compiles to a switch onswitch followed by anhashCode() check, so it is both fast and correct.equals
How compareTo orders strings
compareTosortTreeMapTreeSet
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:
"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:
is -1, and for the prefix'a' - 'b' it is the length difference 3 - 5 = -2. Only the sign is specified, so testapp , never< 0 .== -1 - All capitals come before all lowercase letters, because
is 90 and'Z' is 97. Accented letters such as'a' (233) come afteré , soz sorted last.été.txt - Digits compare as characters, so
sorts before"10" and"9" beforefile10 . Thefile2 comparator compares runs of digits by value, giving the order a file manager shows.numberAware sorts by a key first and breaks ties with a second comparator.Comparator.comparing(String::length).thenComparing(...)- Natural order throws
on a null element.NullPointerException orComparator.nullsFirst wraps a comparator to place nulls explicitly.nullsLast - Because
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.compareTo
For writing comparators in general, see
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.
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:
"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
is 25, socompareToIgnoreCase("Zoo", "apple") now sorts afterZoo .apple treatsCASE_INSENSITIVE_ORDER andAlice as equal, so their order after sorting depends on the input order (the sort is stable). Addingalice makes the result fully determined.thenComparing(naturalOrder())- A
withTreeMap keeps one key per name whatever its case, countingCASE_INSENSITIVE_ORDER andAlice twice each. It keeps the first spelling it saw as the key.Bob - Such a comparator is inconsistent with equals: a
using it holds 3 names and findsTreeSet , while aALICE of the same input, which usesHashSet , holds 5 and does not. Mixing the two kinds of set for the same data gives contradictory answers.equals compares one char at a time, converting each to upper and then lower case. That handlesequalsIgnoreCase andÉ , but noté againstß , which needs two characters.SS- Lowercasing with a Turkish locale turns
into dotlessI , soı is false."TITLE".toLowerCase(tr).equals("title") does not use a locale and is not affected. When you do convert case for comparison, useequalsIgnoreCase .Locale.ROOT
Language-aware order with Collator
People expect ÉvaEvazackCollator
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:
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ë]
put capitals first and accented names last. Case-insensitive order fixed the capitals but still putcompareTo andémile afterÉva . The French collator gave dictionary order, with accented letters next to their base letters.Zoë- The strength decides which differences count.
compares only base letters, soPRIMARY ,Eva andeva are all equal.Éva also counts accents, andSECONDARY , the default, also counts case.TERTIARY - Rules depend on the language: Swedish treats
as a separate letter afterä , while German sorts it withz . Use the locale of the people reading the list.a - A
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.CollationKey
CollatorCollator
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.
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:
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
has an overload with an offset, sostartsWith checks the text at index 7.startsWith("2026", 7) is false forendsWith(".pdf") . Lowercasing the whole name works but copies it..PDF compares a range ignoring case without copying, which theregionMatches(true, ...) helper uses.endsWithIgnoreCase is true only for length 0, whileisEmpty() (Java 11) is also true for whitespace-only strings. Both throw on null. SeeisBlank()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.
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):
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
took about the same time.CASE_INSENSITIVE_ORDER was more than twenty times slower. A sort makes millions of comparisons, and each one runs the full language rules on both strings.Collator.compare- Building a
for each name once and sorting the keys was about six times faster than using the collator directly, while still slower than natural order.CollationKey
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
| Question | Use |
|---|---|
| Same text? | a.equals(b) |
| Same text, either may be null? | Objects.equals(a, b)"CONSTANT".equals(input) |
| Same text, ignoring case? | a.equalsIgnoreCase(b) |
Same text as a StringBuilder | s.contentEquals(sb) |
| Same object? | a == b |
| Order for code, maps and files | compareToComparator.naturalOrder() |
| Order ignoring case | String.CASE_INSENSITIVE_ORDER |
| Order for people | Collator.getInstance(locale)CollationKey |
| Numbers inside names | A number-aware comparator |
| Same text with different accents encoding | Normalize first; see |