Convert Long into Integer
To convert a Long object to an Integer, use the intValue() method:
This is safe only when the Long value is inside Integer's limits (-2,147,483,648 to 2,147,483,647). If the value exceeds this range, you'll encounter overflow.
Handling nulls and overflow
Here, you might face two main issues: null value and possible overflow. To handle null values, a ternary operator can be used:
For arresting overflow, Math.toIntExact() comes to the rescue:
Diverse conversion methods
Sometimes, simple intValue doesn't cut the mustard. Let's explore some more conversion strategies:
-
Integer.valueOf(long)can be utilized for an explicit conversion: -
Ints.checkedCast()from Google's Guava library safely checks for an overflow while casting:
Performance quirks
Here are few points to ponder about performance:
-
Unpacking the
Longand casting it seems simple, but it adds an unnecessary operation. -
Using
Math.toIntExact()has overflow checks built-in but it slows things down due to exception handling. -
A ternary operator with null checks is light, but it adds a conditional statement.
Always weigh the performance cost against the convenience they offer.
Being range conscious
An important point to remember during conversion is the 32-bit range limit of Integer. Going outside this range while converting will result in unexpected outcomes or precision loss.
The magic of auto-unboxing
In some situations, the compiler does this conversion magic called auto-unboxing:
Be aware though, this illusion crashes if your Long value is null.
Choose according to your scenario
Depending on the scenario, your conversion approach may differ:
- For painless safety checks, stick with
Math.toIntExact()unless performance is crucial. - When dealing with possible
nullvalues, use a ternary operator to provide a default value. - Need to handle overflow and already using Guava in your project?
Ints.checkedCast()is your go-to function. - For a simple and direct conversion within safe bounds, you can't go wrong with
intValue().
Was this article helpful?