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








