How to convert a Long value into an Integer value in Java?
If you are using Java 8 Do it as below
import static java.lang.Math.toIntExact;
public class DateFormatSampleCode {
public static void main(String[] args) {
long longValue = 1223321L;
int longTointValue = toIntExact(longValue);
System.out.println(longTointValue);
}
}
Integer i = theLong != null ? theLong.intValue() : null;
or if you don't need to worry about null:
// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;
And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).
Java 8 has a helper method that checks for overflow (you get an exception in that case):
Integer i = theLong == null ? null : Math.toIntExact(theLong);