Signup/Sign In

Java Float valueOf(String s) Method

Java valueOf(String s) method is a part of the Float class of the java.lang package. This method is used to return the equivalent Float object of the string value passed as an argument. It must be noted that the value returned by this method can be interpreted as new Float(Float.parseFloat(s)).

Syntax:

public static Float valueOf(String s) throws NumberFormatException

Parameters:

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

Exception:

NumberFormatException: This exception occurs when the input string is not parsable.

Returns:

Returns the Float object of the String value passed as parameter.

Example 1:

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

import java.lang.Float;

public class StudyTonight 
{  
    public static void main(String[] args)
    {  
        String s1 = "909.89f";
        String s2 = "-253.67f";
        String s3 = "NaN";
            
        System.out.println("Equivalent Float object Value = " + Float.valueOf(s1));//returns a Float object representing the String specified 
        System.out.println("Equivalent Float object Value = " + Float.valueOf(s2));   
        System.out.println("Equivalent Float object Value = " + Float.valueOf(s3));     
    }  
} 


Equivalent Integer object Value = 909.89
Equivalent Integer object Value = -253.67
Equivalent Integer 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 string value");
            Scanner sc=new Scanner(System.in);
            String x = sc.next();
            System.out.println("Equivalent Float object Value = " + Float.valueOf(x));//returns a Float object representing the string specified 
        }
        catch(NumberFormatException e)
        {
            System.out.println("Invalid input!!");
        }
    }  
} 


Enter the string value
NaN
Equivalent Integer object Value = NaN
************************************
Enter the string value
9.45
Equivalent Float object Value = 9.45
************************************
Enter the string value
0x690
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.