Google News
logo
Java Program to convert long type variables into int
In the following examples of Java program that demonstrates how to convert long type variables to int :
Program :
public class LongToIntExample {
    public static void main(String[] args) {
        long num1 = 2147483647L; // maximum int value as long
        long num2 = 3000000000L; // larger than maximum int value
        int intNum1 = (int) num1; // convert long to int
        int intNum2 = (int) num2; // convert long to int
        System.out.println(intNum1); // output: 2147483647
        System.out.println(intNum2); // output: -1294967296 (integer overflow)
    }
}
Output :
2147483647
-1294967296
In this program, we have defined two long variables num1 and num2 with the values 2147483647L (maximum value of int as a long) and 3000000000L (larger than maximum value of int), respectively.

We then assign these variables to int variables intNum1 and intNum2 using the type casting operator (int), which converts the long values to int. However, the second conversion leads to an integer overflow since the value of num2 is larger than the maximum value of int. In such cases, the result will be an unpredictable value.

Finally, we print the values of intNum1 and intNum2 using the System.out.println() method.

The output of the first conversion is 2147483647, which is the maximum value of int.

The output of the second conversion is -1294967296, which is an unpredictable value due to integer overflow.