Signup/Sign In
LAST UPDATED: AUGUST 25, 2020

Java Float byteValue() Method

Java byteValue() method belongs to the Float class of the java.lang package and overrides the byteValue() method of the Number class. This method returns the byte equivalent of the Float object after a narrowing primitive conversion(Conversion of higher data type into lower data type).

In short, this method is used to convert a Float object into a byte value.

Syntax:

public byte byteValue()  

Parameter:

It does not take any parameter.

Returns:

The numerical equivalent of the object of a byte type is created after conversion.

Example 1:

Here, using the byteValue() function and float values are converted into its numerical byte equivalent.

import java.lang.Float;

public class StudyTonight
{  
    public static void main(String[] args) 
      {  
        //converting float object into byte
          Float x = 34f;
          byte i=x.byteValue();
          System.out.println(" Equivalent byte value is " +i);
          
          
          Float y = 19.67f;  
          byte d = y.byteValue();  
          System.out.println(" Equivalent byte value is " +d);
      }  
}


Equivalent byte value is 34
Equivalent byte value is 19

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent byte value.

import java.util.Scanner;  
public class StudyTonight
{  
    public static void main(String[] args) 
    {  
         try
           {
              System.out.print("Enter the value to be converted : ");  
              Scanner sc = new Scanner(System.in);  
              float i = sc.nextFloat();  
              Float n = i ;  
              byte val = n.byteValue();  
              System.out.println("Byte Value is: " + val);  
           }
         catch(Exception e)
           {
              System.out.println("not a valid float"); 
           }
    }
}


Enter the value to be converted : 57.22
Byte Value is: 57
*************************************************
Enter the value to be converted : 0x945
not a valid float

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.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.