How can I convert a long to int in Java?


How can I convert a long to int in Java?

8/17/2012 1:39:07 PM

Long x = 100L;
int y = x.intValue();


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


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;

If using Guava library, there are methods Ints.checkedCast(long) and Ints.saturatedCast(long) for converting long to int.


long x = 3;
int y = (int) x;

but that assumes that the long can be represented as an int, you do know the difference between the two?


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]