Chirag Parmar Chirag Parmar - 4 months ago 38
Java Question

Java - Is it possible for equals() to return false, even if contents of two Objects are same?

I know this is the duplicate question but that question was not asked correctly so I did not the get the answer.
But I was being asked this question in one interview.
I want to know is it possible? If yes, can anyone provide me the code how?

Thanks in advance.

Answer

In java the method public boolean equals(Object obj) is inherited from the Object.class. Since all Java objects inherit (eventually) from Object, they all inherit that method as well. However, the implementation of the method as defined in the Object class is that the equals method will return if and only if the two objects being compared are the same instance.

public class WrappedString {
    private final String str = "hello";
}

public void foo() {
    WrappedString ws1 = new WrappedString();
    WrappedString ws2 = new WrappedString();
    System.out.println(ws1.equals(ws2));
}

The output of the above code snippet will be false since ws1 will only be equal to itself (e.g. other references to the same instance since equals is not overridden).

Comments