Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (3.9k points)
How to convert a Long value into an Integer value in Java?

1 Answer

0 votes
by (46k 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);

Related questions

Browse Categories