Introduction
In this lab, you will learn how to check if a floating-point number is "Not a Number" (NaN) in Java. We will explore the Double.isNaN() method, understand how NaN values are generated through floating-point operations, and consider how to handle non-floating-point inputs in the context of NaN checks. By the end of this lab, you will be equipped to reliably detect and manage NaN values in your Java programs.
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.javafile 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
doublevariables,result1andresult2. result1is assigned the result of0.0 / 0.0, which is an indeterminate form and will produce NaN.result2is assigned the result of10.0 / 2.0, which is a standard number (5.0).- We then use
Double.isNaN()to check ifresult1andresult2are NaN and print the results.
- We declare two
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 compileCheckNaN.java. Open the Terminal and run:javac CheckNaN.javaIf the compilation is successful, you should see no output.
Finally, run the compiled program:
java CheckNaNYou should see output similar to this:
Is result1 NaN? true Is result2 NaN? falseThis output confirms that
Double.isNaN()correctly identifiedresult1as NaN andresult2as 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.
Test with Floating-Point Operations
In this step, we will explore more examples of floating-point operations that can result in NaN and practice using Double.isNaN() to check for them. Understanding which operations produce NaN is crucial for writing robust Java code that handles potential errors gracefully.
Besides dividing zero by zero, other operations involving infinity or invalid mathematical functions can also produce NaN. Java has special representations for positive and negative infinity (Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY).
Let's modify our CheckNaN.java program to test some of these cases.
Open the
CheckNaN.javafile 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; // NaN double result2 = Math.sqrt(-1.0); // NaN (square root of a negative number) double result3 = Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY; // NaN double result4 = 10.0 / 0.0; // Positive Infinity double result5 = -10.0 / 0.0; // Negative Infinity double result6 = 5.0; // Regular number System.out.println("Is result1 NaN? " + Double.isNaN(result1)); System.out.println("Is result2 NaN? " + Double.isNaN(result2)); System.out.println("Is result3 NaN? " + Double.isNaN(result3)); System.out.println("Is result4 NaN? " + Double.isNaN(result4)); System.out.println("Is result5 NaN? " + Double.isNaN(result5)); System.out.println("Is result6 NaN? " + Double.isNaN(result6)); } }In this updated code:
result1is still0.0 / 0.0.result2usesMath.sqrt(-1.0), which is mathematically undefined for real numbers and results in NaN.result3subtracts positive infinity from positive infinity, another indeterminate form resulting in NaN.result4andresult5demonstrate division by zero, which results in positive or negative infinity, not NaN.result6is a simple number for comparison.
Save the file (Ctrl+S or Cmd+S).
Compile the modified program in the Terminal:
javac CheckNaN.javaAgain, no output indicates successful compilation.
Run the program:
java CheckNaNYou should see output similar to this:
Is result1 NaN? true Is result2 NaN? true Is result3 NaN? true Is result4 NaN? false Is result5 NaN? false Is result6 NaN? falseThis output shows that
Double.isNaN()correctly identified the three operations that result in NaN, while correctly identifying the infinity values and the regular number as not NaN.
By testing with these different floating-point operations, you gain a better understanding of when NaN can occur and how to use Double.isNaN() to handle these cases in your programs.
Handle Non-Floating-Point Inputs
In the previous steps, we focused on how floating-point operations can result in NaN. However, sometimes you might receive input that is not a valid number at all, such as text. When you try to convert such input into a floating-point number, it can also lead to issues.
While Double.isNaN() is specifically for checking the result of floating-point calculations, it's also important to handle cases where the initial input cannot be parsed as a number. Java provides methods to parse strings into numbers, and these methods can throw exceptions if the input is invalid.
Let's create a new program that attempts to parse user input as a double and then checks if the parsed value is NaN.
Create a new file in the
~/projectdirectory namedParseAndCheck.java. You can do this by right-clicking in the File Explorer and selecting "New File", then typingParseAndCheck.java.Open the
ParseAndCheck.javafile in the WebIDE editor and add the following code:import java.util.Scanner; public class ParseAndCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a floating-point number or an expression (e.g., 0.0/0.0): "); String input = scanner.nextLine(); try { double value = Double.parseDouble(input); if (Double.isNaN(value)) { System.out.println("The input resulted in NaN."); } else { System.out.println("The input is a valid number: " + value); } } catch (NumberFormatException e) { System.out.println("Invalid input: Could not parse as a number."); } finally { scanner.close(); } } }Let's break down this code:
- We import the
Scannerclass to read user input. - We prompt the user to enter a string.
- We use a
try-catchblock to handle potential errors during parsing. Double.parseDouble(input)attempts to convert the input string into adouble. If the string is not a valid number format (e.g., "hello"), it will throw aNumberFormatException.- Inside the
tryblock, if parsing is successful, we then useDouble.isNaN(value)to check if the resultingdoubleis NaN. - The
catchblock catches theNumberFormatExceptionand prints an error message if the input couldn't be parsed. - The
finallyblock ensures the scanner is closed.
- We import the
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac ParseAndCheck.javaRun the program:
java ParseAndCheckThe program will prompt you for input. Try entering different values:
Enter
5.5:Enter a floating-point number or an expression (e.g., 0.0/0.0): 5.5 The input is a valid number: 5.5Enter
0.0/0.0:Enter a floating-point number or an expression (e.g., 0.0/0.0): 0.0/0.0 Invalid input: Could not parse as a number.(Note:
parseDoublecannot evaluate mathematical expressions directly. It only parses string representations of numbers.)Enter
NaN:Enter a floating-point number or an expression (e.g., 0.0/0.0): NaN The input resulted in NaN.Enter
hello:Enter a floating-point number or an expression (e.g., 0.0/0.0): hello Invalid input: Could not parse as a number.
This step demonstrates how to combine input parsing with the Double.isNaN() check to handle various types of input, including valid numbers, the string "NaN", and invalid number formats. This is a more complete approach to dealing with potential issues when working with floating-point numbers from external sources.
Summary
In this lab, we learned how to check if a floating-point number is "Not a Number" (NaN) in Java. We discovered that NaN is a special value resulting from undefined or unrepresentable calculations, and that standard comparison operators do not work reliably with NaN.
We specifically focused on using the Double.isNaN() method, which is the standard and recommended way to accurately detect NaN values in Java. We demonstrated its usage with examples involving floating-point operations that produce NaN and regular numeric results.



