Java Program to convert long type variables into int

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java Program to Convert long to int using Typecasting

class Main {
  public static void main(String[] args) {

    // create long variables
    long a = 2322331L;
    long b = 52341241L;

    // convert long into int
    // using typecasting
    int c = (int)a;
    int d = (int)b;

    System.out.println(c);    // 2322331
    System.out.println(d);    // 52341241
  }
}

In the above example, we have long type variables a and b. Notice the lines,

int c = (int)a;

Here, the higher data type long is converted into the lower data type int. Hence, this is called narrowing typecasting. To learn more, visit Java Typecasting.

This process works fine when the value of the long variable is less than or equal to the maximum value of int (2147483647). However, if the value of the long variable is greater than the maximum int value, then there will be a loss in data.


Example 2: long to int conversion using toIntExact()

We can also use the toIntExact() method of the Math class to convert the long value into an int.

class Main {
  public static void main(String[] args) {

    // create long variable
    long value1 = 52336L;
    long value2 = -445636L;

    // change long to int
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);

    // print the int value
    System.out.println(num1);  // 52336
    System.out.println(num2);  // -445636
  }
}

Here, the Math.toIntExact(value1) method converts the long variable value1 into int and returns it.

The toIntExact() method throws an exception if the returned int value is not within the range of the int data type. That is,

// value out of range of int
long value = 32147483648L

// throws the integer overflow exception
int num = Math.toIntExact(value);

To learn more on toIntExact() method, visit Java Math.toIntExact().


Example 3: Convert object of the Long class to int

In Java, we can also convert the object of wrapper class Long into an int. For this, we can use the intValue() method. For, example,

class Main {
  public static void main(String[] args) {

    // create an object of Long class
    Long obj = 52341241L;

    // convert object of Long into int
    // using intValue()
    int a = obj.intValue();

    System.out.println(a);    // 52341241
  }
}

Here, we have created an object of the Long class named obj. We then used the intValue() method to convert the object into int type.

To learn more about wrapper class, visit the Java Wrapper Class.

Did you find this article helpful?