== vs equals() in Java
== compares references; equals compares content; equalsIgnoreCase.
if (role == "admin") check passes every unit test. In production, with roles read from a database, it fails for everyone. Same text, different answer — why?Two different questions
For objects, == asks "is this the very same object?" equals() asks "do these hold the same value?" Picture two printed copies of the same book: same words (equals → true), but two physical books (== → false).
Same words, different books
What prints?
String a = new String("Hi");
String b = "Hi";
System.out.println(a == b);
System.out.println(a.equals(b));true truefalse truefalse falsetrue false
Show the answer
false, then true. new made a separate object, so the references differ. String overrides equals to compare the characters, which match.
When case shouldn't matter
equals is case-sensitive: 'Y' and 'y' are different characters. When users might type YES, Yes or yes, use equalsIgnoreCase.
"Yes".equals("yes"); // false
"Yes".equalsIgnoreCase("YES"); // trueWorks in tests, fails in production
In tests, role is often a literal, and literals share one pooled object — so role == "admin" happens to be true. Text from a database, a file or the keyboard arrives as a new String object, so == is false even though the text matches. equals works in both cases.
Comparing user input
if (input == "yes") {
confirm();
}Compares addresses. Fails for runtime text.
if ("yes".equals(input)) {
confirm();
}Compares characters, and is safe even if input is null.
In real projects
String == is such a common bug that IntelliJ, SpotBugs and Sonar all flag it automatically. It's also a favorite interview warm-up: "What's the difference between == and equals?" Now you can answer with the book analogy and the pool explanation.
Key takeaways
- == compares references (same object?)
- equals compares characters (same text?)
- equalsIgnoreCase ignores upper/lower case differences
- == on Strings may pass in tests and fail on real input
💡 == asks 'is this the same book?'; equals asks 'do these books have the same words?'.
String.equals starts with a shortcut: if (this == anObject) return true;. If both sides are the very same object, it answers instantly without comparing a single character.
Practice questions
What does this print?
String a = new String("Java");
String b = "Java";
System.out.println(a.equals(b));
System.out.println(a == b);- true true
- false false
- true false
- false true
Check your answer
true false. equals compares the text, which matches. a is a separate object created by new, so == is false.
What does this print?
String h = "Hello";
System.out.println(h.equalsIgnoreCase("hELLO"));
System.out.println(h.equals("hello"));- true false
- true true
- false false
- false true
Check your answer
true false. equalsIgnoreCase treats upper and lower case as the same; plain equals is case-sensitive, so 'H' and 'h' differ.