Signup/Sign In

Java Float valueOf(float f) Method

Java valueOf(float f) method is part of the Float class of the java.lang package. This method is used to return the equivalent Float object of the float value passed as an argument.

Syntax:

public static Float valueOf(float f)  

Parameters:

The parameter passed is the float value whose equivalent Float object is to be returned.

Returns:

Returns the Float object of the float value passed as a parameter.

Example 1:

Here, the Float object representations are returned of the float value passed.

import java.lang.Float;

public class StudyTonight 
{  
    public static void main(String[] args)
    {  
        float n1 = 35.96f;  //initialization of Float object
        float n2 = -45.564f;
        float n3 = Float.POSITIVE_INFINITY; 
        float n4 = Float.NEGATIVE_INFINITY;  
        float n5 =Float.NaN;  

        //returns a Float object representing the float specified              
        System.out.println("Equivalent Float object Value = " + Float.valueOf(n1));
        System.out.println("Equivalent Float object Value = " + Float.valueOf(n2));
        System.out.println("Equivalent Float object Value = " + Float.valueOf(n3));
        System.out.println("Equivalent Float object Value = " + Float.valueOf(n4));
        System.out.println("Equivalent Float object Value = " + Float.valueOf(n5));
    }  
} 


Equivalent Float object Value = 35.96
Equivalent Float object Value = -45.564
Equivalent Float object Value = Infinity
Equivalent Float object Value = -Infinity
Equivalent Float object Value = NaN

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 x = sc.nextFloat();
            System.out.println("Equivalent Float object Value = " + Float.valueOf(x));//returns a Float object representing the float specified 
        }
        catch(Exception e)
        {
             System.out.println("Invalid input!!");
        }
    }  
}


Enter the value
NaN
Equivalent Float object Value = NaN
*******************************************
Enter the value
78.23
Equivalent Float object Value = 78.23
*******************************************
Enter the value
0x595
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.