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.
Setting up the project
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.
Creating a Long object
In this step, you will create a Long object using a numeric constant.
// creating a Long object
Long num = 12345L;
Converting 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();
Displaying the result
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);
Testing the program
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
Taking user input
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();
Converting user input to 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();
Displaying the result
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);
Testing the modification
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.
Cleaning up
Remove the LongFloatValueMethod.java file using the following command:
rm ~/project/LongFloatValueMethod.java
Summary
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.



