How can I convert a long to int in Java?
Solution 1:
Updated, in Java 8:
Math.toIntExact(value);
Original Answer:
Simple type casting should do it:
long l = 100000;
int i = (int) l;
Note, however, that large numbers (usually larger than 2147483647
and smaller than -2147483648
) will lose some of the bits and would be represented incorrectly.
For instance, 2147483648
would be represented as -2147483648
.
Solution 2:
Long x = 100L;
int y = x.intValue();
Solution 3:
For small values, casting is enough:
long l = 42;
int i = (int) l;
However, a long
can hold more information than an int
, so it's not possible to perfectly convert from long
to int
, in the general case. If the long
holds a number less than or equal to Integer.MAX_VALUE
you can convert it by casting without losing any information.
For example, the following sample code:
System.out.println( "largest long is " + Long.MAX_VALUE );
System.out.println( "largest int is " + Integer.MAX_VALUE );
long x = (long)Integer.MAX_VALUE;
x++;
System.out.println("long x=" + x);
int y = (int) x;
System.out.println("int y=" + y);
produces the following output on my machine:
largest long is 9223372036854775807
largest int is 2147483647
long x=2147483648
int y=-2147483648
Notice the negative sign on y
. Because x
held a value one larger than Integer.MAX_VALUE
, int y
was unable to hold it. In this case, it wrapped around to the negative numbers.
If you wanted to handle this case yourself, you might do something like:
if ( x > (long)Integer.MAX_VALUE ) {
// x is too big to convert, throw an exception or something useful
}
else {
y = (int)x;
}
All of this assumes positive numbers. For negative numbers, use MIN_VALUE
instead of MAX_VALUE
.
Solution 4:
Since Java 8 you can use: Math.toIntExact(long value)
See JavaDoc: Math.toIntExact
Returns the value of the long argument; throwing an exception if the value overflows an int.
Source code of Math.toIntExact
in JDK 8:
public static int toIntExact(long value) {
if ((int)value != value) {
throw new ArithmeticException("integer overflow");
}
return (int)value;
}
Solution 5:
If using Guava library, there are methods Ints.checkedCast(long)
and Ints.saturatedCast(long)
for converting long
to int
.