Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

Double.NaN == Double.NaN

donald rieck
Ranch Hand
Posts: 75
I just don't know,

This prints out a False and then a true:

1: Double a = new Double(Double.NaN);
2: Double b = new Double(Double.NaN);
3:
4: if( Double.NaN == Double.NaN )
5: System.out.println("True");
6: else
7: System.out.println("False");
8:
9: if( a.equals(b) )
10: System.out.println("True");
11: else
12: System.out.println("False");

How can two special values be different?

Keith Lynn
Ranch Hand
Posts: 2409
It's documented in the API.

NaN is the only quantity which is not equal to itself.

This is from the documentation for Double.

Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if

d1.doubleValue() == d2.doubleValue()

also has the value true. However, there are two exceptions:

* If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false.

donald rieck
Ranch Hand
Posts: 75
Thank you Keith!

I found it and put the API close at my side:

/*
Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if

d1.doubleValue() == d2.doubleValue()

also has the value true. However, there are two exceptions:

* If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false.
* If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0==-0.0 has the value true.

This definition allows hash tables to operate properly.

Overrides:
equals in class Object

*/

vineela kom
Greenhorn
Posts: 7
equals() method compares the value in that object.Whereas, == compares the address of the object.

Bear Bibeault
Author and ninkuma
Marshal
Posts: 64623
86
"sriya",

You have previously been warned on one or more occasions regarding adjusting your display name to meet JavaRanch standards. This is not optional. Please take a look at the JavaRanch Naming Policy and adjust your display name to match it prior to your next post.

Be aware that accounts with invalid display names are removed.

bear
JavaRanch Sheriff
[ November 12, 2006: Message edited by: Bear Bibeault ]