0 votes
1 view
ago in Java by (1.8k points)
How to convert a Long value into an Integer value in Java?

1 Answer

0 votes
ago by (21.7k points)

Integer i = theLong != null ? theLong.intValue() : null;

or if you don't require to suffer regarding null:

// auto-unboxing does not go from 

Long to int directly, so

Integer i = (int) (long) theLong;

And in both circumstances, you sway run into overflows (because a Long can get a wider variety than an Integer).

Java 8 has a helper way that verifes for overflow (you get an exception in that case):

Integer i = theLong == null ? null : Math.toIntExact(theLong);

...