Convert Long into Integer

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


Solution 1:

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);

Solution 2:

Here are three ways to do it:

Long l = 123L;
Integer correctButComplicated = Integer.valueOf(l.intValue());
Integer withBoxing = l.intValue();
Integer terrible = (int) (long) l;

All three versions generate almost identical byte code:

 0  ldc2_w <Long 123> [17]
 3  invokestatic java.lang.Long.valueOf(long) : java.lang.Long [19]
 6  astore_1 [l]
 // first
 7  aload_1 [l]
 8  invokevirtual java.lang.Long.intValue() : int [25]
11  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
14  astore_2 [correctButComplicated]
// second
15  aload_1 [l]
16  invokevirtual java.lang.Long.intValue() : int [25]
19  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
22  astore_3 [withBoxing]
// third
23  aload_1 [l]
// here's the difference:
24  invokevirtual java.lang.Long.longValue() : long [34]
27  l2i
28  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
31  astore 4 [terrible]

Solution 3:

For non-null values:

Integer intValue = myLong.intValue();

Solution 4:

If you care to check for overflows and have Guava handy, there is Ints.checkedCast():

int theInt = Ints.checkedCast(theLong);

The implementation is dead simple, and throws IllegalArgumentException on overflow:

public static int checkedCast(long value) {
  int result = (int) value;
  checkArgument(result == value, "Out of range: %s", value);
  return result;
}

Solution 5:

If you are using Java 8 Do it as below

    import static java.lang.Math.toIntExact;

    public class DateFormatSampleCode {
        public static void main(String[] args) {
            long longValue = 1223321L;
            int longTointValue = toIntExact(longValue);
            System.out.println(longTointValue);

        }
}