This post will discuss how to check if double is equal to NaN in Java.

A Not-a-Number (NaN) value can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic. In Java, you can’t compare NaN with a float or a double using the == operator, as per the IEEE 754 floating-point standard.

1. Using isNaN() method

The Double class provides a static method isNaN(double) which returns true if the specified number is a NaN, false otherwise.

Download  Run Code

Output:

Not a Number

 
Depending on the variable type, you can either use the Double.isNaN(double) or Float.isNaN(float) method.

Download  Run Code

Output:

Not a Number

 
If you’re using the Double object instead of a primitive double, you can directly call the isNaN() method on it.

Download  Run Code

Output:

Not a Number

2. Using != operator

Another approach is to compare the double value with itself using the != operator. If the value is NaN, it returns true, since only NaN evaluates false with itself. This approach is used by the isNaN() method, but it lacks readability and might cause confusion for other programmers.

Download  Run Code

Output:

Not a Number

3. Using Double.isFinite() method

Finally, you can use the Double.isFinite() method that returns true for finite floating-point value and false for NaN and infinity. The following code demonstrates its usage.

Download  Run Code

Output:

Not a Number

 
Note that the code returns true not just for Double.NaN, but for Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY as well.

That’s all about checking if double is equal to NaN in Java.