How to convert a Long
value into an Integer
value in Java?
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.
To take input " long long int " and output " long long int " in C is : long long int n; scanf("%lld", &n); printf("%lld", n);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With