Java Program to Convert Long to Int

In this java program, we will learn about how to convert a long variable into a integer(int) value.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Convert long to int using typecasting

In type casting, a data type is converted into another data type explicitly by the programmer. Typecasting in java is performed through typecast operator (datatype).

Long is a larger data type than int, we need to explicitly perform typecasting for the conversion. When converting a higher datatype to lower datatype, it is called narrowing typecasting.

When the long variable's value is less than or equal to the maximum value of int(2147483647), this procedure functions as expected. However, there will be data loss if the long variable's value is higher than the maximum int value.

public class LongToInteger {
  public static void main(String[] args) {
    // Initialize long variable
    long longVal = 2022L;
    // Typecast long to int
    int intVal = (int)longVal;
    System.out.println(intVal);
  }
}
Output
2022

Using intValue() method of Long wrapper class

We can convert Long object to int by intValue() method of Long class. The method does not accept any parameters. Here is the syntax of intValue() method.

public int intValue()
In this program, we will first create an object of the Long class, then used the intValue() method to convert the Long object into int type.

public class LongToInteger2 {
  public static void main(String[] args) {
    // Initialize Long object
    Long longObj = 2022L;
    // Converting Long object to int type
    int intVal = longObj.intValue();
    System.out.println(intVal);
  }
}
Output
2022

Java program to convert long to int using toIntExact()

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

public static int toIntExact(long value)
This method returns the input argument as an int(integer) or throws ArithmeticException, if the result overflows an maximum value of int data type.

public class LongToInteger3 {
  public static void main(String[] args) {
    // Initialize long variable
    long longVal = 1234L;
    // value out of range of int
    long largeLongVal = 32147483648L;

    int intVal = Math.toIntExact(longVal);
    System.out.println(intVal);

    try {
      // It will throw exception
      int intValLarge = Math.toIntExact(largeLongVal);
    } catch (ArithmeticException e) {
      System.out.println(e.getMessage());
    }
  }
}
Output
1234
integer overflow