How can I convert a long to int in Java?
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;
}
Manual typecasting can be done here:
long x1 = 1234567891;
int y1 = (int) x1;
System.out.println("in value is " + y1);
In Java 8 I do in following way
long l = 100L;
int i = Math.toIntExact(l);
This method throws ArithmaticException
if long
value exceed range of int
. Thus I am safe from data loss.
Long x = 100L;
int y = x.intValue();
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
.
Shortest, most safe and easiest solution is:
long myValue=...;
int asInt = Long.valueOf(myValue).intValue();
Do note, the behavior of Long.valueOf
is as such:
Using this code:
System.out.println("Long max: " + Long.MAX_VALUE);
System.out.println("Int max: " + Integer.MAX_VALUE);
long maxIntValue = Integer.MAX_VALUE;
System.out.println("Long maxIntValue to int: " + Long.valueOf(maxIntValue).intValue());
long maxIntValuePlusOne = Integer.MAX_VALUE + 1;
System.out.println("Long maxIntValuePlusOne to int: " + Long.valueOf(maxIntValuePlusOne).intValue());
System.out.println("Long max to int: " + Long.valueOf(Long.MAX_VALUE).intValue());
Results into:
Long max: 9223372036854775807
Int max: 2147483647
Long max to int: -1
Long maxIntValue to int: 2147483647
Long maxIntValuePlusOne to int: -2147483648