# Double.NaN != Double.NaN

The code below does not enter the 'then'...why?

double d = Double.NaN;
if (d == Double.NaN) {
System.out.println ("Does not get here");
}
LVL 1
###### Who is Participating?

Commented:
should use:

if (Double.isNaN(d)) {
0

Commented:
Equality comparison between two NaN numbers is always false.
0

Commented:
When comparing two Double.NaN values, == operator always gives false.

You can use equals function which Double class inherited from Object class:

public boolean equals(Object obj)

Compares this object against the specified object. The result is true if and only if the argument is not null and is a Double object that represents a double that has the identical bit pattern to the bit pattern of the double represented by this object. For this purpose, two double values are considered to be the same if and only if the method doubleToLongBits(double) returns the same long value when applied to each.

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 allows hashtables to operate properly.

Overrides:
equals in class Object

Parameters:
obj - the object to compare with.
Returns:
true if the objects are the same; false otherwis
0

Author Commented:
UrosVidojevic:
Thanks for all the info. I guess I accepted objects answer while you were typing. Sorry.
0

Commented:
It's OK. You are given the right answer, that is important. :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.