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.
- The first is a static method, which takes a float value as an argument.
public static boolean isNaN(float val)
- The second method checks if the value of the current object is
NaN.
public boolean isNaN()
Parameters
val: theFloatobject 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 2System.out.println(val1 +" - " + Float.isNaN(val1)); // defiinition 1System.out.println(val2 +" - " + Float.isNaN(val2));}}
Explanation
In the code above:
-
In line 5, we created a
Floatobject with the nameval1and valuesNaN. -
In line 6, we created another
Floatobject with the nameval12and values1.0f. -
In line 8, we checked if the value of the object
val1isNaNusing the class methodisNaNof theFloatclass. We will gettrueas a result. -
In line 9, we checked if the value of the object
val1isNaNusing the static methodisNaNof theFloatclass. We will gettrueas a result. -
In line 10, we checked if the value of the object
val2isNaNusing the static methodisNaNof theFloatclass. We will getfalseas a result.