Signup/Sign In

Java Float isNaN() method

Java isNaN() method is a part of the Float class of the java.lang package. This method is used to check whether the float value passed is Not-a-Number(NaN) or not. It returns the boolean value true for NaN values and false for non-NaN values.

Syntax:

public boolean isNaN()  

Parameters:

No parameter is passed in this method.

Returns:

Returns the boolean value true for NaN values and false for non-NaN values.

Example 1:

Here, boolean values are returned in accordance with the float value passed as an argument.

import java.lang.Float;

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        Float f1 = 67.78f;  
        Float f2 = 0f; 
        Float f3 = -f1/0.0f;
        Float f4 = f2/0.0f;
        Float f5 = 0.0f/0.0f;
           
        System.out.println("The value is : " +f1.isNaN()); //returns false for finite value  
        System.out.println("The value is : " +f2.isNaN()); //returns false for infinite value 
        System.out.println("The value is : " +f3.isNaN()); //returns false for infinaite value 
        System.out.println("The value is : " +f4.isNaN()); // returns true for NaN value
        System.out.println("The value is : " +f5.isNaN()); // returs true for NaN 
    }  
}    


The value is : false
The value is : false
The value is : false
The value is : true
The value is : true

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.lang.Float;
import java.util.Scanner;

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        try
        {
           System.out.println("Enter the value");
           Scanner sc = new Scanner(System.in);
           float i = sc.nextFloat();
           Float f = i;
          
           boolean b = f.isNaN();
           if(b== true)
           {
             System.out.println("Value is NaN");
           }
           else
           {
             System.out.println("Value is non NaN");
           }
         }
         
         catch(Exception e)
         {
           System.out.println("Invalid Input");
         }      
    } 
}  


Enter the value
NaN
Value is NaN
******************
Enter the value
80455.89
Value is non NaN

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.