Java Number.byteValue() Method
Last Updated :
14 May, 2025
The Number class in Java is an abstract superclass for numeric wrapper classes like Integer, Float, Double, etc. One of the useful methods provided by this class is byteValue(). The Number.byteValue() method in Java is used when we want to extract the byte representation of a numeric object.
The byteValue() method returns the value of the specified number as a byte. As we all know, in Java, the byte type ranges from -128 to 127. So, the actual returned value may involve truncation or rounding depending on the original number.
Syntax of Java Number.byteValue() Method
public byte byteValue()
- Parameters: The method does not take any parameters.
- Return value: This method returns the numeric value represented by this object after conversion to type byte.
Examples of Java Number.byteValue() Method
Example 1: In this example, we are going to use Integer and Float with byteValue() method.
Java
// Java program to demonstrate the
// Number.byteValue() method
import java.lang.Number;
public class Geeks {
public static void main(String[] args) {
// create an Integer object with a large value
Integer n1 = new Integer(12345786);
// convert the Integer to byte
byte b1 = n1.byteValue();
System.out.println("Byte value of Integer 12345786: " + b1);
// create a Float object
Float n2 = new Float(9145876f);
// convert the Float to byte
byte b2 = n2.byteValue();
System.out.println("Byte value of Float 9145876f: " + b2);
}
}
OutputByte value of Integer 12345786: -70
Byte value of Float 9145876f: 20
Explanation: Here, 12345786 exceeds the byte range, so truncation happens and the output is -70. For 9145876f, the same truncation logic applies and it prints 20.
Example 2: In this example, we are going to use smaller numbers with byteValue() method.
Java
// Java program to demonstrate
// Number.byteValue() with small numbers
import java.lang.Number;
public class Geeks {
public static void main(String[] args) {
// create an Integer object within byte range
Integer n1 = new Integer(123);
// convert to byte
byte b1 = n1.byteValue();
System.out.println("Byte value of Integer 123: " + b1);
// create a Float object
Float n2 = new Float(76f);
// convert to byte
byte b2 = n2.byteValue();
System.out.println("Byte value of Float 76f: " + b2);
}
}
OutputByte value of Integer 123: 123
Byte value of Float 76f: 76
Explanation: Here, both values are within the valid byte range.
Important Points:
- This method is very useful when working with APIs or any legacy codes that require data in byte form.
- We should use this method carefully, because for large values, it truncated the result.
- Always make sure that the number you are converting falls within the valid byte range to maintain data accuracy.