This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Double.NaN question" Watch "Double.NaN question" New topic

Double.NaN question

jenny wang

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);
4: if( Double.NaN == Double.NaN )
5: System.out.println("True");
6: else
7: System.out.println("False");
9: if( a.equals(b) )
10: System.out.println("True");
11: else
12: System.out.println("False");
A) True
B) True
C) False
D) False
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13018
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) ==
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.

author of:
I agree. Here's the link:
subject: Double.NaN question
It's not a secret anymore!