Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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-

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading