Advertisement
Advertisement


How can I convert a long to int in Java?


Question

How can I convert a long to int in Java?

2012/08/17
1
325
8/17/2012 1:39:07 PM


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

2014/07/15

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.

2020/08/13

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;
}
2016/04/27

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

2016/09/13

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?

2010/12/04

Source: https://stackoverflow.com/questions/4355303
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]