Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Long into Integer

Tags:

java

How to convert a Long value into an Integer value in Java?

like image 511
Srinivasan Avatar asked Apr 27 '11 12:04

Srinivasan


People also ask

Can we convert long to int in C#?

Since both integer and long are base data types, we can convert from the long data type to the integer data type with the Convert. ToInt32() method in C#. The Convert. ToInt32() method is used to convert any base data type to a 32-bit integer data type.

How do you write an int as long?

To take input " long long int " and output " long long int " in C is : long long int n; scanf("%lld", &n); printf("%lld", n);


1 Answers

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); 
like image 60
Thilo Avatar answered Oct 11 '22 14:10

Thilo