Introduction
In this lab, you will learn how to use the floatValue()
method of the Long
class in Java. The floatValue()
method is used to convert a Long
object into its equivalent float
value.
In this lab, you will learn how to use the floatValue()
method of the Long
class in Java. The floatValue()
method is used to convert a Long
object into its equivalent float
value.
Create a new Java file named LongFloatValueMethod.java
in the ~/project
directory using the following command:
touch ~/project/LongFloatValueMethod.java
Open the LongFloatValueMethod.java
file in a text editor.
Long
objectIn this step, you will create a Long
object using a numeric constant.
// creating a Long object
Long num = 12345L;
Long
to float
In this step, you will use the floatValue()
method to convert the Long
object into a float
value.
// converting Long to float using the floatValue() method
float floatNum = num.floatValue();
In this step, you will display the converted float
value on the console.
// displaying the converted float value
System.out.println("Float value of " + num + " is " + floatNum);
Save the file and compile it using the following command:
javac ~/project/LongFloatValueMethod.java
Run the program using the following command:
java LongFloatValueMethod
The program will display the following output for the Long
value 12345L
:
Float value of 12345 is 12345.0
In this step, you will modify the program to take the Long
value from the user.
// creating a Scanner object to take user input
Scanner sc = new Scanner(System.in);
// prompting the user to enter a long value
System.out.print("Enter a long value: ");
// reading the long value from the user
Long num = sc.nextLong();
float
In this step, you will use the floatValue()
method to convert the user input Long
value into a float
value.
// converting user input Long to float using the floatValue() method
float floatNum = num.floatValue();
In this step, you will display the converted float
value on the console.
// displaying the converted float value
System.out.println("Float value of " + num + " is " + floatNum);
Save the file and compile it using the following command:
javac ~/project/LongFloatValueMethod.java
Run the program using the following command:
java LongFloatValueMethod
The program will prompt you to enter a long value. Enter a long value and press Enter. The program will display the float equivalent of the entered value on the console.
Remove the LongFloatValueMethod.java
file using the following command:
rm ~/project/LongFloatValueMethod.java
In this lab, you learned how to use the floatValue()
method of the Long
class in Java to convert Long
objects into their equivalent float
values. You also learned how to use the Scanner
class to take user input and how to display output on the console using the println()
method.