You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

According to JLS:

"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."

Problems can ensue when the programmer uses such operators on NaN values in comparison operations. There is also a possibility that the input validation condition does not expect a NaN value as input.

Non-compliant Code Example

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

public class NaNComparison {
  public static void main(String[] args) {
    double result = Double.NaN;
    if(result == Double.NaN) 
      System.out.println("Both are equal");
  }
}

Compliant Solution

This compliant solution uses Double.isNaN to check if the expression corresponds to a NaN value.

public class NaNComparison {
  public static void main(String[] args) {
    double result = Double.NaN;
  if(Double.isNaN(result)) 
    System.out.println("Both are equal");
  }
}

References

JLS 4.2.3 Floating-Point Types, Formats, and Values
Findbugs FE: Doomed test for equality to NaN

  • No labels