Introduction
In this lab, we will learn about the byteValue() method of the Float class in Java. The byteValue() method is used to convert a Float object into an equivalent byte value. In other words, it returns the byte equivalent of a Float object after a narrowing primitive conversion.
Creating a Float object
First, we will create a Float object. This Float object will contain a floating-point value that we will use to convert into an equivalent byte value.
Float num = 78.93f;
In the above code, we have created a Float object named num and assigned it a value of 78.93f.
Converting float to byte using byteValue() method
Next, we will use the byteValue() method to convert the Float object num into an equivalent byte value.
byte result = num.byteValue();
The byteValue() method returns the byte equivalent of the Float object, and we have stored this value in a byte variable named result.
Printing the byte value
Now, we will print the result byte value using the System.out.println() method.
System.out.println("Byte value of " + num + " is " + result);
The above code uses string concatenation to format the output string. We have printed the original floating-point value and its equivalent byte value.
Compile and run the program
Save the code to a file named FloatByteValue.java. Then, compile and run the program using the following commands in the terminal:
javac FloatByteValue.java
java FloatByteValue
Here is the full code:
public class FloatByteValue {
public static void main(String[] args) {
// Creating a Float object
Float num = 78.93f;
// Converting float to byte using byteValue() method
byte result = num.byteValue();
// Printing the byte value
System.out.println("Byte value of " + num + " is " + result);
}
}
Output:
Byte value of 78.93 is 78
Summary
In this lab, we learned about the byteValue() method of the Float class in Java. We saw how to use this method to convert a Float object into an equivalent byte value. The method is used to perform a narrowing primitive conversion. We also saw a sample program that demonstrates the use of the byteValue() method.



