Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment

Back to Classroom

NaN

Java Basics Course

Engineers From These Top Companies and Universities Trust EXLskills

1M+ Professionals | 100+ Institutions

This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.

-->

Is this course FREE?

Yes, this a 100% free course that you can contribute to on GitHub here!

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.