← Back to Week 1 Hub

String Comparison: == vs .equals()

Workbook 1c, p.101 — How to correctly compare Strings in Java

Always use .equals() to compare Strings
Use .equalsIgnoreCase() when capitalization should not matter
Never use == to compare String values — it does not always work
Right vs Wrong — Code Examples
✗ Wrong
// Using == to compare Strings if (command == "add") { System.out.println("Adding..."); } // May work sometimes, but BREAKS // with Scanner input!
== checks if two variables point to the exact same object in memory. With Scanner input, Java creates a new object even if the text matches — so == returns false.
✓ Right
// Using .equals() to compare Strings if (command.equals("add")) { System.out.println("Adding..."); } // Always works! Compares the actual // characters in both strings.
.equals() compares the content of both strings — the actual characters. It works correctly regardless of how the string was created.
Try It — String Comparator

vs

==Unreliable
?
Do NOT use for Strings
.equals()
?
.equalsIgnoreCase()
?
Remember: In real Java code, == on Strings from Scanner input will return false even when the text matches. Always use .equals().
Quick Reference — When to Use What
.equals()
Exact match
"Add" matches "Add"
but NOT "add"
.equalsIgnoreCase()
Case-insensitive
"Add" matches "add"
and "ADD"
== AVOID
Checks object identity
Not reliable for Strings
Will cause bugs
Why Does == Sometimes Work?
Short answer: Java reuses identical string literals behind the scenes (called the "String Pool"). So when you write String a = "Hello" and String b = "Hello", both variables point to the same object — and == returns true.

But when you read a string from Scanner, Java creates a brand new object. Even if the user types "Hello", it is a different object from the literal "Hello" in your code. So == returns false even though the characters are identical.

This is why == is a trap — it works in quick tests but breaks in real programs. Always use .equals().

We will explore objects and memory in more detail in a later week.

← Logical Operators Method Signature Anatomy →