Lesson Completion
Back to course

String Comparison: equals, compareTo, and == Pitfall

Beginner
15 minutes4.5Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: equals() compares content, == compares references, compareTo() gives ordering. The #1 Java bug: using == for strings!

When GitHub checks if usernames match: input.equals(storedUsername). Content matters, not memory address!


2. Conceptual Clarity

The Critical Difference

graph LR Equals["equals()"] --> Content["Compares: Characters"] EqEq["=="] --> Reference["Compares: Memory Address"] CompareTo["compareTo()"] --> Order["Compares: Alphabetical Order"] style Content fill:#2E7D32 style Reference fill:#D32F2F

3. Technical Mastery

MethodReturnsUse Case
equals()booleanContent equality
equalsIgnoreCase()booleanCase-insensitive equality
compareTo()intOrdering (neg/0/pos)
==booleanReference equality (avoid!)

4. Interactive & Applied Code

java
public class StringComparison { public static void main(String[] args) { // === equals() vs == === String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false (different objects) System.out.println(s1.equals(s2)); // true ✅ (same content) // Pool strings are special String s3 = "Hello"; String s4 = "Hello"; System.out.println(s3 == s4); // true (same pool object) System.out.println(s3.equals(s4)); // true ✅ (always safe) // === equalsIgnoreCase() === String email1 = "User@Email.com"; String email2 = "user@email.com"; System.out.println(email1.equals(email2)); // false System.out.println(email1.equalsIgnoreCase(email2)); // true ✅ // === compareTo() for ordering === String a = "Apple"; String b = "Banana"; String c = "Apple"; System.out.println(a.compareTo(b)); // Negative (a < b) System.out.println(b.compareTo(a)); // Positive (b > a) System.out.println(a.compareTo(c)); // 0 (equal) // === compareToIgnoreCase() === String x = "apple"; String y = "APPLE"; System.out.println(x.compareTo(y)); // 32 (lowercase > upper) System.out.println(x.compareToIgnoreCase(y)); // 0 (equal ignoring case) // === Null-safe comparison === String nullStr = null; // nullStr.equals("test"); // ❌ NullPointerException! "test".equals(nullStr); // ✅ Returns false safely // Using Objects.equals() (Java 7+) java.util.Objects.equals(nullStr, "test"); // false, no NPE // === Real-world: Login check === String inputPassword = "secret123"; String storedPassword = "secret123"; if (inputPassword.equals(storedPassword)) { System.out.println("Login success!"); } } }

⚠️ Common Mistakes

Mistake #1: Using == for string comparison

java
if (username == "admin") { } // ❌ May fail! if (username.equals("admin")) { } // ✅ Correct

Mistake #2: Calling method on potential null

java
input.equals("value"); // ❌ NPE if input is null "value".equals(input); // ✅ Safe (literal never null)

Mistake #3: Ignoring case when needed

java
email.equals(storedEmail); // ❌ "User@X.com" != "user@x.com" email.equalsIgnoreCase(storedEmail); // ✅

5. The "Interview Corner"

🏆 Q1: "Why does == sometimes work for strings?" Answer: String Pool—literals with same content share the same object. But this isn't guaranteed for all strings! Always use equals().

🏆 Q2: "What does compareTo() return?" Answer:

  • Negative: First string comes before
  • Zero: Equal
  • Positive: First string comes after

🏆 Q3: "How to write null-safe comparison?"

java
// Option 1: Literal first "expected".equals(input); // Option 2: Objects.equals() Objects.equals(a, b);

🎓 Key Takeaways

✅ Always use equals() for string comparison
== compares references, not content
equalsIgnoreCase() for case-insensitive
compareTo() for alphabetical ordering
✅ Put literal first to avoid NullPointerException

Topics Covered

Java FundamentalsStrings

Tags

#java#strings#string-manipulation#string-methods#beginner-friendly

Last Updated

2025-02-01