NaN

Examples of Exceptions

NaN

🙋 Need help? Ask an expert now!

In Java, "NaN" stands for "not a number" and signifies that a value is not defined. "NaN" is not an exception error, but a value that is assigned. For example, imaginary numbers like the square root of negative numbers or zero divided by zero will both print "NaN" as the result. Take a look at the example below.

NaNExample.java
package exlcode;

public class NaNExample {

  public static double exampleVariableOne = -3;

  public static void main(String[] args) {
    // this will print NaN because square root of -3 is an imaginary number
    System.out.println(Math.sqrt(-3));
  }
}

When we attempt to find the square root of a negative number, the program returns "NaN". Contrary to exceptions, a "NaN" result will not cause your program to stop, but may still become an issue if you try to the use the "NaN" result in any other calculations in the program. For example, you will likely throw an error when "NaN", which is not a number, ends up in an expression with an int. Java will throw an error because arithmetic operators cannot be used on two different data types.

Edit Me on GitHub!

Application Question

Which of the following will print "NaN"?




...

You've Reached the End of this Course! 🎓🎉

Great work, are you ready to learn more?

View More Courses