Double a = new Double(Double.NaN)

Double b = new Double(Double.NaN)

A) True

True

B) True

False

C) False

True

D) False

False

Ans given C??

I thought it will give True for first if condn.

We are comparing Double object instance contents.So why is it giving false??

NaN can be the result of certain arithmetic operations for e.g. Dividing 0 by 0 or a square root of a negative number, etc. This result, NaN, indicates an indeterminate number. It is not an ordered number like other floating point values. So NaN is considered non-ordinal for Comparisons.

Explanation given in JLS.

Except for NaN, floating-point values are ordered; arranged from smallest to largest, they are negative infinity, negative finite nonzero values, negative zero, positive zero, positive finite nonzero values, and positive infinity.

NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN . The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN . 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.

Consider the following e.g

public class AverageFruit

{

public static void main(

String[] args)

{

double numOranges = 50.0e-1;

double numApples = 1.0e1;

double average1 = 0.0;

double average2 = 0.0;

double a;

double b;

average1 = (numOranges + numApples) / 0.0;

average2 = (numOranges + numApples) / 0.0;

System.out.println("A totally fruity program");

System.out.println("Average

fruit is " + average1);

System.out.println("Average fruit is " + average2);

if(average1==average2)

System.out.println("Average1 and Average2 are equal");

a = (numOranges - 5.0)/ (numApples - 10.0);

b = (numOranges - 5.0)/ (numApples - 10.0);

System.out.println("The value of a is " + a);

System.out.println("The value of b is " + b);

if(a==b)

System.out.println("a and b are equal");

else

System.out.println("a and b are not equal");

}

}

The value of average1 and average2 is Infinity. It means the result is greater than the largest number that can be represented as type double. In this case the comparison average1==average2 will result in true.

The second calculation with a and b is of type 0/0. This gives indeterminate result. Both will have value NaN. But the result of a==b will result in false.

To summarize:

For any value of x, including NaN itself, all of the following comparisons will return false.

x < Double.NaN<br /> x <= Double.NaN<br /> x == Double.NaN<br /> x > Double.NaN<br /> x >= Double.NaN

NOTE: Double.NaN != Double.NaN will return TRUE.

I hope the above explanation will help you.