Java Convert long to byte
In this Java core tutorial we learn how to convert a long value into byte value with different solutions in Java programming language.
Table of contents
How to cast long to byte in Java
In this first solution, given a long value we just simply cast it to a byte value as the following example Java code.
ConvertLongToByteExample1.java
public class ConvertLongToByteExample1 {
public static void main(String... args) {
long longValue = 99;
// Cast long to byte
byte byteValue = (byte)longValue;
System.out.println("long value: " + longValue);
System.out.println("byte value: " + byteValue);
}
}
long value: 99
byte value: 99
Using Long.byteValue() method
In this second solution, with a given Long object we can use the Long.byteValue() to return the byte value as the following Java code.
ConvertLongToByteExample2.java
public class ConvertLongToByteExample2 {
public static void main(String... args) {
Long longValue = 120L;
// Convert long to byte
byte byteValue = longValue.byteValue();
System.out.println("long value: " + longValue);
System.out.println("byte value: " + byteValue);
}
}
long value: 120
byte value: 120
Happy Coding 😊
Related Articles
Java Convert Long to Hexadecimal String
Java Convert Hexadecimal String to Long