Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# NaN and .equals()

Bert Pritchard
Greenhorn
Posts: 3
Can anyone explain this interesting code:
Double x = Double.NaN;
Double y = Double.NaN;
if (x.equals(y))
System.out.println("Wow, they are equal...");
I would have thought that they would not be equal since Double.NaN != Double.NaN.
Thanks much.
Bert

Ajith Kallambella
Sheriff
Posts: 5782
Have you seen our new Certification FAQ??. You will find the answer there!!
Ajith

Cindy Glass
"The Hood"
Sheriff
Posts: 8521
Actually the FAQ addresses the == behavior of NaN but not the .equals behavior.

Ajith Kallambella
Sheriff
Posts: 5782
In cases like this, the first place to go to is the API documentation. Atleast you will know if something you observe is the expected behaviour.
Here's what I got from Java API documentation

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 while d2 represents -0.0, or vice versa, the equal test has the value false, even though .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 otherwise.

Hope that helps!
Ajith

Chandru kotai
Greenhorn
Posts: 7
I tried to Compile the following
Double x= Double.NaN;
This doesn't work as Double.NaN can be assigned to only Vairables of primitive type (double).I would also like to point out the the equals() method takes objects as aruguments, it does not allow primitive types to be passed as arguments.
Now the follwoing will surely print "True"
Double x= new Double(Double.NaN);
Double y= new Double(Double.NaN);
if (x.equals(y))
System.out.println("True");
Hope this makes Sense. Correct me if I am wrong.

Bert Pritchard
Greenhorn
Posts: 3
Sorry about that. That is the code I had in my test program. I just typed it in a hurry. Thanks for the clarification.

 Consider Paul's rocket mass heater.