Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Mock Q

Shilpa Bhargava
Ranch Hand
Posts: 39
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
Surprisingly the asnwer is C when it should have been the reverse.
Can ne one pls explain

Thanks

Dan Chisholm
Ranch Hand
Posts: 1865
Double.NaN is not equal to anything including itself and the equality operator knows that. The equality operator will always return false when NaN is compared to itself. The Double.equals method does not compare the double values as doubles. Instead, it uses the doubleToLongBits method to change each double value to a set of 64 bits stored in a variable of type long. The Double.equals method then tests the equality of the bit representations of the values. The equals method will return true if the bit representations are the same even if the bit layout represents NaN.

Shilpa Bhargava
Ranch Hand
Posts: 39
Originally posted by Dan Chisholm:
The Double.equals method then tests the equality of the bit representations of the values. The equals method will return true if the bit representations are the same even if the bit layout represents NaN.

Thanks Dan,
Since NaN will never be equal to itself, why are their bit representation same ??
Can you please explain a little further..
[ November 19, 2002: Message edited by: Shilpa Bhargava ]

Jose Botella
Ranch Hand
Posts: 2120
The == operator returns false for NaN ,and equals method returns true; regardless of the bit representation used in Java for NaN.
The API for Float.floatToRawIntBits(float) suggest that a JVM implementation could use several bit patterns for NaN

If the argument is NaN, the result is the integer representing the actual NaN value. Unlike the floatToIntBits method, intToRawIntBits does not collapse all the bit patterns encoding a NaN to a single "canonical" NaN value.

Shilpa Bhargava
Ranch Hand
Posts: 39
So does this mean that NaN can be taken as an exceptional case wherein the even if the bit representation is not same, the equals method will still return true ???

Jose Botella
Ranch Hand
Posts: 2120
I think so. After all how many NaN are wanted in a Set or hash-like container? Only one.

Shilpa Bhargava
Ranch Hand
Posts: 39
Thanks Jose,Thanks Dan !