1

I have the Following code in Java:

class Complex {
    private double re, im;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }
}


public class Main {
    public static void main(String[] args) {
        Complex c1 = new Complex(10, 15);
        Complex c2 = new Complex(10, 15);
        if (c1.equals(c2)) {
            System.out.println("Equal ");
        }
        else 
        {
            System.out.println("Not Equal ");
        }
    }
}

My question: why this program outputs Not Equal?, So the build-in equals method is used for content comparison, and not for adress comparison like == operator. tnx a lot :)

The Head Rush
  • 3,157
  • 2
  • 25
  • 45
  • 3
    You haven't overridden `equals` in your class. – khelwood Oct 29 '18 at 15:11
  • What do you mean by "*built-in*"? The one inherited from `Object` class? – PM 77-1 Oct 29 '18 at 15:13
  • So, if I dont override the equals method, it not should compare the contents of the objects? – Shlomi Elhaiani Oct 29 '18 at 15:17
  • if you don't override it, the Object method is used: `return (this == obj);` Documentation: " The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true)." – user85421 Oct 29 '18 at 15:48

1 Answers1

1

If you haven’t overridden the equals() method in your class, it refers to the equals method in the base class ‘Object’. The default implementation of equals in Object class is a shallow comparison of object references(addresses).

Prasanth Nair
  • 489
  • 3
  • 12
  • 1
    So you mean in this case there is no difference between the non-overriden equals method and the == operator? – Shlomi Elhaiani Oct 29 '18 at 15:20
  • That is what `Object.equals(Object)` does so if you don't override it, it will use `==` only. – Peter Lawrey Oct 29 '18 at 15:32
  • You can see [the default implementation](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Object.java#l148) simply delegates to `==`. One difference to note is that `equals` will throw an NPE if the first object is `null`. But yeah, if you want to have a useful `equals`, you should override it. – TiiJ7 Oct 29 '18 at 15:37