How to convert a Long value into an Integer value in Java?
The best simple way of doing so is:
public static int safeLongToInt( long longNumber )
{
if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE )
{
throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
}
return (int) longNumber;
}
In Java 8 you can use Math.toIntExact. If you want to handle null
values, use:
Integer intVal = longVal == null ? null : Math.toIntExact(longVal);
Good thing about this method is that it throws an ArithmeticException if the argument (long
) overflows an int
.
You'll need to type cast it.
long i = 100L;
int k = (int) i;
Bear in mind that a long has a bigger range than an int so you might lose data.
If you are talking about the boxed types, then read the documentation.
In java ,there is a rigorous way to convert a long to int
not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.
Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);
If you care to check for overflows and have Guava handy, there is Ints.checkedCast():
int theInt = Ints.checkedCast(theLong);
The implementation is dead simple, and throws IllegalArgumentException on overflow:
public static int checkedCast(long value) {
int result = (int) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
In addition to @Thilo's accepted answer, Math.toIntExact
works also great in Optional method chaining, despite it accepts only an int
as an argument
Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0