Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...