What is the difference between == and .equals() for objects?
Quick Answer
== compares object references (identity) — whether two variables point to the same object in memory. .equals() compares logical/content equality and can be overridden to compare field values. For primitives, == compares the values directly since there's no identity concept.
Detailed Answer
== on reference types checks reference identity — are both variables pointing at the exact same object on the heap? .equals() checks logical equality, whatever the class defines it to mean (by default, Object.equals also just does identity comparison, unless overridden).
String a = new String("hi");
String b = new String("hi");
a == b; // false — different objects
a.equals(b); // true — same content
String c = "hi";
String d = "hi";
c == d; // true — both point at the same interned literal in the string pool
For classes like String, wrapper types, and records, .equals() is overridden to compare contents. For custom classes, you must override equals() (and hashCode(), per the equals/hashCode contract) to get meaningful value comparison — otherwise it falls back to identity comparison from Object.
On primitives, == simply compares values, since there's no object identity involved (5 == 5 is always true).
Rule of thumb: use == for primitives and for intentional reference/identity checks (e.g., singleton checks); use .equals() whenever comparing the content of objects.