Signup/Sign In

Java Float isFinite() Method

Java isFinite() method is a part of the Float class of the java.lang package. This method is used to check whether the passed floating value is a finite floating-point value or not. It returns the boolean value true for finite floating values and false for NaN and infinite values.

Syntax:

public static boolean isFinite(float f)  

Parameters:

The parameter passed is the float value f which will be checked if it is finite or not.

Returns:

Returns true if the passed floating value has a finite value and returns false for infinite and NaN values.

Example 1:

Here, the 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 = 578648.67f;  
        float f2 = f1/0.0f; 
        float f3 = -f1/0.0f;
        float f4 = 0X06792345;
        float f5 = 0.0f/0.0f;
                
        System.out.println("The value is : " +Float.isFinite(f1)); //returns true for finite value  
        System.out.println("The value is : " +Float.isFinite(f2)); //returns false for infinite value 
        System.out.println("The value is : " +Float.isFinite(f3)); //returns false for infinaite value 
        System.out.println("The value is : " +Float.isFinite(f4)); // returns true for finite value
        System.out.println("The value is : " +Float.isFinite(f5)); // returs false for NaN 
    }    
}    


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

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 f = sc.nextFloat();
          
           boolean b = Float.isFinite(f);
           if(b == true)
           {
               System.out.println("Value is finite");
           }
           else
           {
               System.out.println("Value is infinite");
           }
         }  
         catch(Exception e)
         {
             System.out.println("Invalid Input");
         }
    }
}  


Enter the value
78.905
Value is finite
*******************
Enter the value
NaN
Value is infinite
*******************
Enter the value
0x000673
Invalid Input

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.