Introduction
The Java Float class is used to wrap a value of primitive types float, into an object. The toString() method of the Float class is used to convert a float type into a String type. This lab will demonstrate how to use the toString() method to convert a float value into a string.
Create a java file
Create a java file with name FloatToStringDemo.java in the ~/project directory:
cd ~/project
touch FloatToStringDemo.java
Write Java code
Add the following Java code to the FloatToStringDemo.java file:
public class FloatToStringDemo {
public static void main(String[] args) {
//creating float variables
float f1 = 2.34f;
//converting float to string
String str = Float.toString(f1);
//printing float variables and converted string
System.out.println("Float Value : " + f1);
System.out.println("String Value : " + str);
}
}
Compile the code
To compile the code, open a terminal, cd into the directory where the FloatToStringDemo.java file is located and run the following command:
javac FloatToStringDemo.java
Run the code
To run the code, use the following command:
java FloatToStringDemo
This will print both the float value and the String value on the console.
User input example
Add the following Java code to the FloatToStringDemo.java file to get user input and demonstrate the toString() method:
import java.util.Scanner;
public class FloatToStringDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//getting float number input from user
System.out.print("Enter a float number: ");
float f = sc.nextFloat();
//converting float to string
String str = Float.toString(f);
//printing both float and converted string
System.out.println("Float Value : " + f);
System.out.println("String Value : " + str);
}
}
Compile and run code
To compile and run the code, use the following commands:
javac FloatToStringDemo.java
java FloatToStringDemo
This will fulfill the user input example.
Summary
In this lab, you learned about the Java Float class and demonstrated how to use the toString() method to convert a float value into a String. By following step-by-step instructions, you learned how to write, compile, and run Java code.



