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 The correct answer is C. Why? A Not-a-Number (NaN) value of type double. It is equal to the value returned by Double.longBitsToDouble(0x7ff8000000000000L).
NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (�15.20.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (�15.21.1). In particular, x!=x is true if and only if x is NaN, and (x<y) == !(x>=y) will be false if x or y is NaN.
Moreover, we'd like you to read the Javaranch Naming Policy and change your publicly displayed name to comply with the rules. Thank you for your cooperation. We hope you'll stay around.
Valentin, Thank you very much. But as for the second if, I think Double value must be changed to double for such comparison. then for the two value of double, it should return false. why is the comparision result is true? thank you. BTW, Ranch is a good place. I've been watching it for a while. and today is the first time I post messge here. lydia
Joined: Aug 26, 2001
lydia, thank you for changing your displayed name. as for your question, try to use the JLS and the API, you'd have got your answer in two mouse clicks: From the API (class Double, method equals):
... If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false. ...
To understand why the equals method returns true, look at the source code for java.lang.Double.equals() You will see that it actually compares the long bits (not double values) and that comparison does not care about the special treatment of NaN.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com