String Comparison in Java

Naveen AnamaneniUpdated · 4 min read

A login page checks whether the typed password matches; a contact list sorts names alphabetically; a search box ignores capital letters. Each needs a different kind of string comparison, and Java has a method for each. The most important lesson here is the one that catches every beginner: == does not compare text.

Four Ways to Compare

Pick the comparison that matches your question
Compare.java▶ Try it
public class Compare {
    public static void main(String[] args) {
        String typed = new String("Navika");
        String saved = "Navika";
        String lower = "navika";
 
        System.out.println(typed == saved);
        System.out.println(typed.equals(saved));
        System.out.println(saved.equals(lower));
        System.out.println(saved.equalsIgnoreCase(lower));
 
        System.out.println("Advitha".compareTo("Navika"));
        System.out.println("Srihitha".compareTo("Navika"));
        System.out.println("Navika".compareTo("Navika"));
    }
}
Output
false
true
false
true
-13
5
0

How it works

  1. == checks whether two variables point to the same object. typed is a separate object, so it's false, even though the text is identical.
  2. equals compares the characters, one by one. Same text: true.
  3. equals is case-sensitive: "Navika" and "navika" differ.
  4. equalsIgnoreCase treats capital and small letters as the same.
  5. compareTo tells you the order: negative if the first string comes before the second, zero if equal, positive if it comes after. "Advitha" comes before "Navika", so the result is negative.

Why == Seems to Work Sometimes

With two literals, "a" == "a" is true, because both point to the same pooled object (see "Strings in Java"). That's exactly what makes == dangerous: it passes your quick test, then fails as soon as one string comes from user input, a file, a database or a + at runtime. Text from those sources is a separate object every time.

How compareTo Decides the Order

compareTo walks both strings from the start and stops at the first different character. It returns the difference between those two characters' Unicode values:

ComparisonFirst differenceResult
"Advitha" vs "Navika"'A' (65) vs 'N' (78)65 - 78 = -13
"Srihitha" vs "Navika"'S' (83) vs 'N' (78)83 - 78 = 5
"Nav" vs "Navika"One string ends firstdifference in length: -3
"apple" vs "Apple"'a' (97) vs 'A' (65)32: all capitals sort before all small letters

Only the sign matters to sorting; don't rely on the exact number. Because capital letters come first, "Zebra" sorts before "apple". Use compareToIgnoreCase, or a Comparator such as String.CASE_INSENSITIVE_ORDER, for human-friendly order.

Comparing Safely with null

Calling equals on a null reference throws. Compiled with -g (as IDEs and build tools do), the message names the variable:

Terminal output
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "city" is null

Two simple fixes:

TechniqueExample
Put the known literal first"Pune".equals(city) returns false when city is null
Use Objects.equalsObjects.equals(city, "Pune") handles null on either side

Common Mistakes

if (password == savedPassword). Use equals.

city.equals("Pune") when city might be null. Write "Pune".equals(city).

Expecting compareTo to return exactly -1 or 1. Test the sign: < 0, == 0, > 0.

Interview Corner

What is the difference between == and equals() for strings?

== compares references: it's true only if both variables point to the same object. equals compares the character content and is true whenever the text is the same. Two equal literals may be == because of the String pool, but strings created at runtime or with new are separate objects, so equals is the correct way to compare text.

What does compareTo return?

A negative number if this string comes before the argument in lexicographic (Unicode) order, zero if they're equal, and a positive number if it comes after. It's computed from the first differing character, or from the lengths if one string is a prefix of the other.

Practice

  1. Easy: Ask for a password with Scanner and check it against "Java@25" with equals. Then try == and explain the result.
  2. Harder: Sort the array {"srihitha", "Navika", "advitha"} with Arrays.sort, print it, then sort it again with String.CASE_INSENSITIVE_ORDER. Explain the difference.

Quick check: String comparison

4 questions
1Which compares two strings' text?
2"Apple".equalsIgnoreCase("apple") is:
3"Advitha".compareTo("Navika") is:
4Which is null-safe when city may be null?

Key Takeaways

Was this tutorial helpful?

Lesson 191 of 482