long to byte Java


After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast long to byte as an example.

The byte takes 1 byte of memory and long takes 8 bytes of memory. Assigning 8 bytes of memory to 1 byte of memory requires explicit casting. This is known as narrowing conversion.

byte –> short –> int –> long –> float –> double

The left-side value can be assigned to any right-side value and is done implicitly. The reverse like long to byte requires explicit casting.

Examples of implicit casting

int x = 10; // 4 bytes
long y = x; // 4 bytes to 8 bytes

byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes

Following program on long to byte explains explicit casting. Observe, the Java synyax where long is casted to byte.
public class Conversions
{
  public static void main(String args[])
  {
    long l1 = 10;                 // 8 bytes
    // byte b1 = l1;              // error,  8 bytes to 1 byte
          
    byte b1 = (byte) l1;          // 8 bytes long is type converted to 1 byte value byte explicitly

    System.out.println("long value: " + l1);                 // prints 10
    System.out.println("Converted byte value: " + b1);       // prints 10
  }
}


long to byte
Output screenshot of long to byte Java

byte b1 = l1;

The above statement raises a compilation error "possible loss of precision".

byte b1 = (byte) l1;

The long l1 is explicitly type casted to byte b1. Observe, the syntax of explicit casting. On both sides, it should be byte only.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.