What's the most idiomatic way in Java to verify that a cast from 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; }
You can cast a long to int so long as the number is less than 2147483647 without an error.
Java int can be converted to long in two simple ways:Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.
In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.
One of the foremost concerns related to casting in Java refers directly to the two type groups in Java. The two types of groups are primitive and reference. The first attention of this discourse would go to the casting of primitives to ensure type conversion.
A new method has been added with Java 8 to do just that.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With