What is the best way to avoid data loss when converting from long to int?
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;
}
This is what I've implemented.
java casting
A new method has been added in Java 8.
import static java.lang.Math.toIntExact;
long foo = 10L;
int bar = toIntExact(foo);
If it overflows, throws an error called ArithmeticException. In Java 8, a safe method has been added to these overflows, all ending with exact.
© 2024 OneMinuteCode. All rights reserved.