aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Double.NaN question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Double.NaN question" Watch "Double.NaN question" New topic
Author

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: 12825
    
    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:
 
wood burning stoves
 
subject: Double.NaN question