How to Convert Long to Int in Java


How can we convert a long to an integer in Java?

long longNum = 100; // <-- convert this

Keep in mind that a long can hold more information (larger numbers) than an int, so if the long holds a value greater than an int can hold, it may not be converted correctly.

1. Using Math.toIntExact()

If we’re in Java 8, we can use Math.toIntExact(long).

int i = Math.toIntExact(longNum);

This method will throw an exception if the value overflows an int.

2. Using a primitive cast

We could also use a simple primitive cast.

int i = (int) longNum;

We can add our own exception handler in this scenario.

int i;
if (longNum > (long) Integer.MAX_VALUE || longNum < (long) Integer.MIN_VALUE) {
    // Throw an exception
} else {
    i = (int) longNum;
}

3. Using Guava

If we’re using Guava, we can use Ints.checkedCast(long) or Ints.saturatedCast(long) to convert from long to int.

int i = Ints.checkedCast(longNum);
int j = Ints.saturatedCast(longNum);

This method will throw an exception if the value overflows an int.