long to int Java

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

The long takes 8 bytes of memory and int take 4 bytes of memory. Assigning 8 bytes of memory to 4 bytes of memory requires explicit casting.

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 int 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 explains explicit casting, Java style where long is type converted to int.

public class LongToInt
  public static void main(String args[])
    long l1 = 10;                     // 8 bytes
    // int i1 = l1;                   // error, 8 bytes long to 4 bytes int
    int i1 = (int) l1;                // 8 bytes long is type converted to 4 bytes int

    System.out.println("Long value: " + l1);               // prints 10
    System.out.println("Converted to int value: " + i1);   // prints 10

Output screenshot of long to int Java

int i1 = l1;

The above statement raises a compilation error as 8 bytes value is assigned to 4 bytes and requires explicit casting (the statement is commented out in the code).

int i1 = (int) l1;

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

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.