liveBook · Manning

Nan

As explained in 100 Java Mistakes and How to Avoid Them

NaN is a special floating-point value representing an undefined or unrepresentable numeric result and that is unequal to every value, including itself.

NaN (“not a number”) is a special floating-point value for an undefined or unrepresentable numeric result. In Java, Double.NaN and Float.NaN are unequal to every value, including themselves. section 4.15.2

The comparison trap

Comparing directly with NaN never detects it: both Double.NaN == Double.NaN and Float.NaN == Float.NaN print false. Use Double.isNaN(value) or Float.isNaN(value) instead. section 4.15.2

NaN can also enter comparisons implicitly. A method that handles a < b, a > b, and otherwise assumes equality treats any NaN operand as the equality case, producing unexpected results. section 4.15.2

Avoid NaN-related failures by:

  • Checking possible NaN inputs whenever floating-point values are compared. section 4.15.2
  • Using assertions for internal assumptions and preconditions for public APIs. section 4.15.2
  • Using Double.compare() or comparingDouble() instead of manually implementing floating-point ordering. section 7.12
  • Testing fields that may contain NaN, or rejecting NaN during assignment when it is invalid. section 7.12

Ordering objects safely

A manual comparator using d == o.d ? 0 : d < o.d ? -1 : 1 violates its contract when d is NaN. return Double.compare(d, o.d) handles NaN and also orders 0.0 relative to -0.0. section 7.12

void process(double a, double b) {
  if (a < b) {
    … // Process the a < b case.
  } else if (a > b) {
    … // Process the a > b case.
  } else {
    … // Process the a == b case.
  }
}

Inspect how a three-way relational branch accidentally routes NaN operands into its equality case. section 4.15.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines NaN, demonstrates comparison failures, and prescribes validation and library-based ordering without deriving floating-point internals.
Examples
Uses self-comparison, three-way branching, manual Comparable ordering, Double.compare, assertions, and NaN-rejecting constructors.
What you can do after
Diagnose NaN comparison bugs, validate inputs, and implement floating-point ordering with standard library methods.
How it connects
Connects NaN with floating-point comparison, Comparable, Comparator, preconditions, assertions, overflow, and underflow.

Also explained in

Compare how 9 books explain nan →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.