Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

A frequently encountered mistake is the doomed comparison with NaN, typically in expressions. As per its semantics, no value (including NaN itself) can be compared to NaN using common operators. This noncompliant example demonstrates one of such the many violations.

Code Block
bgColor#FFcccc
public class NaNComparison {
  public static void main(String[] args) {
    double x = 0.0;
    double result = Math.cos(1/x); // returns NaN if input is infinity
    if(result == Double.NaN) // compare with infinity
      System.out.println("Both are equal");
  }
}

...