Java Convert long to byte

Tags: long 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

  1. How to cast long to byte in Java
  2. Using Long.byteValue() method

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);
    }
}
The output as below.
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);
    }
}
The output as below.
long value: 120
byte value: 120

Happy Coding 😊

Java Convert byte to long

Java Convert long to char

Java Convert char to long

Java Convert Long to Hexadecimal String

Java Convert Hexadecimal String to Long

Java Convert Long to Octal String

Java Convert Octal String to Long