Home > Blockchain >  What am I getting wrong about Java's '==' and '.equals'?
What am I getting wrong about Java's '==' and '.equals'?

Time:09-06

EDIT: I'm new to java and am going through the official documentation in preparation for an upcoming subject in my Computer Science studies.

Original question:

So I checked this thread re: java == and .equals and am getting some unexpected results in dummy code that I'm writing.

I have this:

public class HelloWorld {
    public static void main(String[] args){
        Double double1 = 1.0;  //object 1
        Double double2 = 1.0;  //object 2, which should be a different memory address?

        System.out.println(double1.equals(double2)); //compare using the Object.equals() method 
        System.out.println(double1 == double2); //compare with ==
    }
}
//Results are:
//true
//false

As expected, == produces a false because the two objects refer to different memory addresses.

However the double.equals(double2) is producing a true, which is not what I expected. In this example, I'm not overriding the default .equals() inherited from Object. My understanding is that equals checks for reference equality as well as values.

So why does double1.equals(double2) return true instead of false in this example? Are't double1 and double2 referring to two difference objects and therefore equals() should return false?

CodePudding user response:

You didn't override equals, but the implementation of java.lang.Double does override it, to return true if the underlying values compare equal (plus a couple of edge cases).

https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#equals-java.lang.Object-

CodePudding user response:

My understanding is that equals checks for reference equality as well as values.

That is incorrect.

The version of equals(Object) defined by java.lang.Object does that. But many classes override equals(Object) to have different semantics.

Double overrides it, and so do all of the other "primitive wrapper" classes, and String ... and many, many more.

The semantics of the override are typically equal-by-value, but not always. And some classes don't override equals. Examples where equals is not overridden that trip people up are StringBuilder and array types!

To find out the semantics for SomeType.equals(Object) you need to start with the javadocs for SomeType ... not Object.

  • Related