| Author |
Double.NaN ???
|
lydia westland
Ranch Hand
Joined: Feb 24, 2002
Posts: 72
|
|
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). Thank you
|
Lydia<br />~~~~~~~~~~~~<br />I love Italy team.
|
 |
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
|
|
lydia, Welcome to Javaranch, a friendly place for Java greenhorns To answer your question, JLS 4.2.3 Floating-Point Types, Formats, and Values
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.
|
SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
|
 |
lydia westland
Ranch Hand
Joined: Feb 24, 2002
Posts: 72
|
|
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
|
 |
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
|
|
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. ...
Glad you enjoy it around here
|
 |
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 12267
|
|
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. Bill
|
Java Resources at www.wbrogden.com
|
 |
 |
|
|
subject: Double.NaN ???
|
|
|