Advertisement
Beginner Java, Java Fundamentals: Syntax, Data Types & Operators

What is the difference between the == operator and the .equals() method when comparing two custom objects, if the class hasn't overridden equals()?

Short answer

For any class that hasn't overridden equals() (inheriting Object's default implementation), == and .equals() behave IDENTICALLY -- both perform simple reference identity comparison, checking whether both variables point to the exact same object instance in memory -- .equals()…

Save Java mock interview
Advertisement
AModel answer
For any class that hasn't overridden equals() (inheriting Object's default implementation), == and .equals() behave IDENTICALLY -- both perform simple reference identity comparison, checking whether both variables point to the exact same object instance in memory -- .equals() only behaves differently from == once a class provides its own meaningful override comparing actual field values instead, meaning for a plain, unmodified custom class, using == or the inherited .equals() produces the exact same result either way.
public class Point {
    int x, y;
    // No equals() override
}

Point p1 = new Point();
Point p2 = new Point();
System.out.println(p1 == p2);        // false -- different instances
System.out.println(p1.equals(p2));   // ALSO false -- default equals() just delegates to ==

Point p3 = p1;
System.out.println(p1 == p3);         // true -- same instance
Real-world example
A developer confused about why two Point objects with identical x/y coordinate values aren't considered equal learns that without an explicit equals() override, both == and the inherited .equals() perform identical reference-identity comparison, requiring a proper equals() override to achieve the intended value-based comparison instead.
Likely follow-ups
  • At what point does overriding equals() actually cause .equals() to diverge in behavior from ==?
  • Why does Object provide a default equals() implementation that's functionally identical to == rather than some other default behavior?
Related topics