What is Float.isNaN() in Java?

The isNaN method of the Float class is used to check if the specified Float number is a NaN (Not-a-Number) value.

Syntax

There are two methods available to check if the float value is NaN.

  1. The first is a static method, which takes a float value as an argument.
public static boolean isNaN(float val)
  1. The second method checks if the value of the current object is NaN.
public boolean isNaN()

Parameters

  • val: the Float object passed to the first definition of the function.
  • The second definition does not take any parameters as it is called on the specified object itself.

Return value

This method returns true if the value is NaN. Otherwise, it returns false.

Code

The code below uses the isNaN method.

class FloatIsNaN {
public static void main(String args[])
{
Float val1 = Float.NaN;
Float val2 = 1.0f;
System.out.println(val1 +" - " + val1.isNaN()); // definition 2
System.out.println(val1 +" - " + Float.isNaN(val1)); // defiinition 1
System.out.println(val2 +" - " + Float.isNaN(val2));
}
}

Explanation

In the code above:

  • In line 5, we created a Float object with the name val1 and values NaN.

  • In line 6, we created another Float object with the name val12 and values 1.0f.

  • In line 8, we checked if the value of the object val1 is NaN using the class method isNaN of the Float class. We will get true as a result.

  • In line 9, we checked if the value of the object val1 is NaN using the static method isNaN of the Float class. We will get true as a result.

  • In line 10, we checked if the value of the object val2 is NaN using the static method isNaN of the Float class. We will get false as a result.

Free Resources