I was just studying OCPJP questions and I found this strange code:
public static void main(String a[]) {
System.out.println(Double.NaN==Double.NaN);
System.out.println(Double.NaN!=Double.NaN);
}
When I ran the code, I got:
false
true
How is the output false when we're comparing two things that look the same as each other? What does NaN mean?
NaN means "Not a Number".
Java Language Specification (JLS) says:
Floating-point operators produce no exceptions (ยง11). An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN.