== compares object references (memory addresses). equals() compares object content/values.
Analogy: == asks "are these two people the same person?" (identity). equals() asks "do these two people have the same name and info?" (equality).
== operator:
equals() method:
Object class — default implementation uses == (reference equality).1// Example 1: Two different String objects2String s1 = new String("hello");3String s2 = new String("hello");45s1 == s2; // FALSE — different objects in memory6s1.equals(s2); // TRUE — same content78// Example 2: String literals (string pool)9String s3 = "hello";10String s4 = "hello";1112s3 == s4; // TRUE — same object in string pool13s3.equals(s4); // TRUE — same content1415// Example 3: Custom class without equals()16class Person {17 String name;18 Person(String name) { this.name = name; }19}2021Person p1 = new Person("Alice");22Person p2 = new Person("Alice");2324p1 == p2; // FALSE — different objects25p1.equals(p2); // FALSE — uses default Object.equals() which is ==
Overriding equals() correctly:
1class Person {2 private String name;3 private int age;45 public Person(String name, int age) {6 this.name = name;7 this.age = age;8 }910 @Override11 public boolean equals(Object obj) {12 // Same reference → equal13 if (this == obj) return true;1415 // Null or different class → not equal16 if (obj == null || getClass() != obj.getClass()) return false;1718 // Cast and compare fields19 Person other = (Person) obj;20 return this.age == other.age21 && Objects.equals(this.name, other.name);22 }2324 @Override25 public int hashCode() {26 return Objects.hash(name, age);27 }28}2930Person p1 = new Person("Alice", 30);31Person p2 = new Person("Alice", 30);32p1.equals(p2); // TRUE — content is equal
Critical rule: equals() + hashCode() contract:
equals(), you must override hashCode().1// WRONG: override equals() but not hashCode()2Set<Person> set = new HashSet<>();3set.add(new Person("Alice", 30));4set.add(new Person("Alice", 30));5set.size(); // 2 — WRONG! Should be 1 (hashCode differs)
Common mistakes:
== when you need value equality.equals() on primitives (it doesn't work — use ==).equals() without overriding hashCode().null in equals() (always check for null).instanceof instead of getClass() (allows subclasses to sneak in).