Java - long type and int type cast

Cast between int type and long type

When a long literal is assigned to a variable of type long, the Java compiler checks the value and ensures that it is in the range of the long data type; otherwise it generates a compile time error.

For example, the following code generates a compiler error.

The following code tries to assign one more value than maximum positive value for long. This will generate a compiler error.

long num1 = 9223372036854775808L; 
  

Since the int data type has a smaller range than long data type, the value stored in an int variable can always be assigned to a long variable.

  
int num1 = 10; 
long num2 = 20; // OK to assign int literal 20 to a long variable num2 
num2 = num1;    // OK to assign an int to a long 

You cannot simply assign the value stored in a long variable to an int variable. There is a possibility of value overflow.

For example,

int num1 = 10; 
long num2 = 92233720368547L; 
  

If you assign the value of num2 to num1 as

num1 = num2; 

the value stored in num2 cannot be stored in num1, since the data type of num1 is of type int and the value of num2 falls outside the range of int data type.

Java will generate a compile-time error for the following statement

num1 = num2; 
  

Even if the value stored in a long variable is well within the range of the int data type, the assignment from long to int is not allowed:

int num1 = 5; 
long num2 = 5L; 
num1 = num2; 

To assign the value of a long variable to an int variable, use "cast" in Java:

  
num1 = (int)num2; 

The following code shows the result of casting.

Demo

public class Main {
  public static void main(String[] args) {
    int num1 = 5; 
    long num2 = 5L; 

    System.out.println(num1);//from w  w  w.j  a  v  a 2 s .c  o m
    System.out.println(num2);
    
    num1 = (int)num2; 

    System.out.println(num1);
    System.out.println(num2);
    
    num1 = 5; 
    num2 = 92233720368547L; 

    System.out.println(num1);
    System.out.println(num2);
    
    num1 = (int)num2; 

    System.out.println(num1);
    System.out.println(num2);
    
    
    
  }
}

Result