Intellipaat Back

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

0 votes
1 answer
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...