LAST UPDATED: AUGUST 25, 2020
Java Float floatValue() Method
Java floatValue()
method belongs to the Float
class of the java.lang
and is inherited from the Number
Class. It is an instance method that returns the floating equivalent of the specified number.
It is generally an Unboxing method. Although after the introduction of Java 5, the conversion is done automatically(autoboxing), but it is important for you to know the concept of Boxing and Unboxing.
Unboxing: Conversion of a Float
to float
is referred to as the unboxing
Boxing: Conversion of an float
to Float
is referred to as boxing.
Syntax:
public float floatValue()
Parameter:
No parameter is passed in this method.
Returns:
Returns the floating value of the object after it is converted into the float.
Example 1:
Here, using the floatValue()
function, the Float object is converted into its float equivalent.
import java.lang.Float;
public class StudyTonight
{
public static void main(String[] args)
{
Float n1 = 25.5f;
Float n2 = 46.2f;
float i = n1.floatValue(); // returns the value of the Float object n1 as an float
float j = n2.floatValue(); // returns the value of the Float object n2 as an float
System.out.println("float value is " + i);
System.out.println("float value is " + j);
}
}
float value is 25.5
float value is 46.2
Example 2:
Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent float value.
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.print("Enter The Value ");
Scanner sc = new Scanner(System.in);
Float f = sc.nextFloat();
Float n = f;
System.out.println("Float Value is: " + n.floatValue()); //Converting the Float object into float
}
catch(Exception e)
{
System.out.println(" Invalid Input!!");
}
}
}
Enter The Value 352.4
Float Value is: 352.4
****************************
Enter The Value 0x77
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.