patternjavaCritical
Safely casting long to int in Java
Viewed 0 times
safelyjavalongintcasting
Problem
What's the most idiomatic way in Java to verify that a cast from
This is my current implementation:
long to int does not lose any information?This is my current implementation:
public static int safeLongToInt(long l) {
int i = (int)l;
if ((long)i != l) {
throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
}
return i;
}Solution
A method was added in Java 8:
Will throw an
See:
Several other overflow safe methods have been added to Java 8. They end with exact.
Examples:
import static java.lang.Math.toIntExact;
long foo = 10L;
int bar = toIntExact(foo);Will throw an
ArithmeticException in case of overflow.See:
Math.toIntExact(long)Several other overflow safe methods have been added to Java 8. They end with exact.
Examples:
Math.incrementExact(long)
Math.subtractExact(long, long)
Math.decrementExact(long)
Math.negateExact(long),
Math.subtractExact(int, int)
Code Snippets
import static java.lang.Math.toIntExact;
long foo = 10L;
int bar = toIntExact(foo);Context
Stack Overflow Q#1590831, score: 659
Revisions (0)
No revisions yet.