This week's book giveaway is in the Android forum.We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Head First Android this week in the Android forum!

# Double.NaN question

jenny wang
Greenhorn

Joined: Feb 23, 2001
Posts: 27
Can anybody tell me why(the reason) C is right for following question?
The following code will print
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");
A) True
True
B) True
False
C) False
True
D) False
False
Jenny
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12982

5
Ewww that is tricky! We know that Double.NaN == Double.NaN as a comparison of double values returns false, so naturally we expect the equals method to fail too.
Unfortunately, the Double equals method is:
public boolean equals(Object obj) {
return (obj != null)
&& (obj instanceof Double)
&& (doubleToLongBits(((Double)obj).value) ==
doubleToLongBits(value));
}
which instead of comparing double == double uses the doubleToLongBits conversion so the == ends up comparing the bit patterns - which are equal. This unexpected result IS cited in the Javadocs.
Bill

------------------
author of:

subject: Double.NaN question