Topic: Programming in Java
What is the output of this floating-point NaN comparisons?
public class Test {
public static void main(String []args)
{
double d1 = Double.NaN; double d2 = Double.NaN;
System.out.println((d1 == d2) + " " +
Double.valueOf(d1).equals(Double.valueOf(d2)));
}
}
- A. true true
- B. false true
- C. false false
- D. true false
Answer: B. false true
Explanation: According to IEEE 754 floating-point standards, `NaN == NaN` always evaluates to `false`. However, the `Double.equals()` method in Java is specifically designed to treat two `Double.NaN` objects as equal to satisfy the contract of the `equals` method, so it evaluates to `true`.