String Comparison in Java
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
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"));
}
}false
true
false
true
-13
5
0How it works
==checks whether two variables point to the same object.typedis a separate object, so it'sfalse, even though the text is identical.equalscompares the characters, one by one. Same text:true.equalsis case-sensitive:"Navika"and"navika"differ.equalsIgnoreCasetreats capital and small letters as the same.compareTotells 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:
| Comparison | First difference | Result |
|---|---|---|
"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 first | difference 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:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "city" is nullTwo simple fixes:
| Technique | Example |
|---|---|
| Put the known literal first | "Pune".equals(city) returns false when city is null |
Use Objects.equals | Objects.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
- Easy: Ask for a password with
Scannerand check it against"Java@25"withequals. Then try==and explain the result. - Harder: Sort the array
{"srihitha", "Navika", "advitha"}withArrays.sort, print it, then sort it again withString.CASE_INSENSITIVE_ORDER. Explain the difference.
Key Takeaways
Was this tutorial helpful?