String Comparison
1. Three Ways (beginner must-master!)
== (addresses — WRONG for content!), .equals() (content — CORRECT!), compareTo() (ordering: dictionary rank).
2. Code — The Proof (run this once, remember forever!)
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false (different houses!)
System.out.println(a.equals(b)); // true (same furniture!)
System.out.println("apple".compareTo("banana")); // negative (a < b)
System.out.println("hi".compareTo("hi")); // 0 (equal!)
System.out.println("b".compareTo("a")); // positive (b > a)
System.out.println("Hi".equalsIgnoreCase("hi")); // true (case ignored!)
| Method | Compares | Returns |
|---|---|---|
== |
addresses | true only if same object! |
.equals() |
content | true if same letters |
compareTo() |
dictionary order | 0 equal, <0 before, >0 after |
equalsIgnoreCase() |
content, no case | true for Hi/hi |
3. Traps (exam's favourite trap of all time!)
new String("hi") == new String("hi")is false (two houses!). Always.equals()for content.- Literals
"hi" == "hi"is true (pool accident — shared!). Don't rely on it! compareTois case-sensitive:"A"(65) <"a"(97).
4. Exam Points
==vs.equals()vscompareTowith output — 7 marks, all-time favourite.- Login check with
.equals()— 3 marks, frequent.