In Java, you can convert an int
value to a byte
using the byteValue()
method of the Byte
class or by using a type cast.
Here is an example of how to convert an int
to a byte
using the byteValue()
method:
int number = 128; byte b = Byte.valueOf((byte) number).byteValue(); // b is -128
In this example, the int
value is first cast to a byte
, and then the byteValue()
method is used to retrieve the byte
value.
You can also use a type cast to convert an int
to a byte
directly:
int number = 128; byte b = (byte) number; // b is -128
The type cast operator (byte)
converts the int
value to a byte
by discarding the higher-order bits and keeping the lower 8 bits. This can cause the value to be truncated or sign-extended, depending on the value of the int
.
For more information on converting data types in Java, you can refer to the Java documentation.