Use Double.isNaN() for Check
In this step, we will learn how to check if a floating-point number is "Not a Number" (NaN) in Java using the Double.isNaN()
method.
Floating-point numbers in computers can sometimes result in a special value called NaN. This happens when the result of a calculation is undefined or cannot be represented as a standard number. For example, dividing zero by zero or taking the square root of a negative number can result in NaN.
It's important to be able to detect NaN values in your programs because they behave differently from regular numbers. For instance, comparing a NaN value with any other number (even another NaN) using standard comparison operators (==
, <
, >
) will always result in false
.
Java provides a specific method to check for NaN: Double.isNaN()
. This method takes a double
value as input and returns true
if the value is NaN, and false
otherwise.
Let's create a simple Java program to demonstrate how to use Double.isNaN()
.
-
Open the HelloJava.java
file in the WebIDE editor.
-
Replace the existing code with the following:
public class CheckNaN {
public static void main(String[] args) {
double result1 = 0.0 / 0.0; // This will result in NaN
double result2 = 10.0 / 2.0; // This is a regular number
System.out.println("Is result1 NaN? " + Double.isNaN(result1));
System.out.println("Is result2 NaN? " + Double.isNaN(result2));
}
}
In this code:
- We declare two
double
variables, result1
and result2
.
result1
is assigned the result of 0.0 / 0.0
, which is an indeterminate form and will produce NaN.
result2
is assigned the result of 10.0 / 2.0
, which is a standard number (5.0).
- We then use
Double.isNaN()
to check if result1
and result2
are NaN and print the results.
-
Save the file (Ctrl+S or Cmd+S).
-
Now, we need to compile this new program. Since we changed the class name to CheckNaN
, we need to compile CheckNaN.java
. Open the Terminal and run:
javac CheckNaN.java
If the compilation is successful, you should see no output.
-
Finally, run the compiled program:
java CheckNaN
You should see output similar to this:
Is result1 NaN? true
Is result2 NaN? false
This output confirms that Double.isNaN()
correctly identified result1
as NaN and result2
as a regular number.
Using Double.isNaN()
is the correct and reliable way to check for NaN values in Java. Relying on direct comparison (== Double.NaN
) is not recommended because, as mentioned earlier, NaN == NaN
evaluates to false
.