Comparing doubles in Java gives strange results
I really don't understand why the following happens:
Double d = 0.0; System.out.println(d == 0); // is true System.out.println(d.equals(0)); // is false ?!
However, this is working as expected:
Double d = 0.0; System.out.println(d == 0.0); // true System.out.println(d.equals(0.0)); // true
I'm sure it's related to some way auto@R_530_2419 @Ing, but I really don't know why 0 will be used in different ways using the = = operator and When equals is called
Isn't this an implicit violation of the equality contract?
* It is reflexive: for any non-null reference value * x,x.equals(x) should return * true.
Edit:
Thank you for your quick answer I think it's a different box. The real question is: why is it boxed differently? I mean, if d = = 0d is more intuitive and expected than d.equals (0d), then it will be more intuitive, but if d = = 0 looks like an integer, it should be true than "intuitive" d.equals (0)
Solution
Just change it
System.out.println(d.equals(0d)); // is false ?! Now true
You are comparing with integer 0
Under the cover
System.out.println(d.equals(0)); // is false ?!
0 will be automatically boxed as an integer, and an instance of integer will be passed to the equals () method of the double class, which will be more like
@Override public boolean equals(Object object) { return (object == this) || (object instanceof Double) && (doubleToLongBits(this.value) == doubleToLongBits(((Double) object).value)); }
Of course, it will return false
to update
When you use = = for comparison, it compares values, so you don't need to auto@R_530_2419 @, which operates directly on values Where equals () accepts object, so if you try to call D1 Equals (0), then 0 is not an object, so it will perform automatic boxing and package it as an integer, which is an object