Java - Float Class valueOf() Method

Float class valueOf() method: Here, we are going to learn about the valueOf() method of Float class with its syntax and example. By Preeti Jain Last updated : March 21, 2024

Syntax

public static Float valueOf (float value);
public static Float valueOf (String value);

Float class valueOf() method

  • valueOf() method is available in java.lang package.
  • valueOf (float value) method is used to represent the Float object denoted by the given argument (value) is of float type.
  • valueOf (String value) method is used to represent Float object holding the float value denoted by the given argument (value) is of String type.
  • valueOf (float value) method does not throw an exception at the time of returning an instance.
  • But, valueOf (String value) method may throw an exception at the time of returning an instance.
    • NullPointerException: In this exception, if we pass a null value as an argument.
    • NumberFormatException: In this exception, if we don't pass the number as an argument.
  • valueOf(float value) and valueOf(String value) are the static methods, they are accessible with the class name too and, if we try to access the method with the class object then also we will not get an error.

Parameters

  • In the first case, float value - This parameter represents the value of float type.
  • In the second case, “String value - This parameter represents the value of String type.

Return Value

In the first case, the return type of this method is Float - it returns the Float representation of this float argument.

In the second case, the return type of this method is Float - it returns the Float representation of this String argument.

Example

// Java program to demonstrate the example 
// of valueOf() method of Float class

public class ValueOfFloatClass {
    public static void main(String[] args) {
        // Object initialization
        Float ob1 = new Float("10.20f");
        Float ob2 = new Float("20.20f");

        // Display ob1,ob2 values
        System.out.println("ob1: " + ob1);
        System.out.println("ob2: " + ob2);

        // It returns Float object holding the value 
        // denoted by the given float argument
        Float value1 = ob1.valueOf(20.10f);

        // String object initialization for valueOf(String s)
        String s = "80";

        // It returns Float object holding the value 
        // denoted by the given String argument
        Float value2 = ob2.valueOf(s);

        // Display result values
        System.out.println("ob1.valueOf(20.10f): " + value1);
        System.out.println("ob2.valueOf(s): " + value2);
    }
}

Output

ob1: 10.2
ob2: 20.2
ob1.valueOf(20.10f): 20.1
ob2.valueOf(s): 80.0

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.