...
This compliant solution validates that the value stored in the wider integer type is within the range of the narrower type before converting to the narrower type. It throws an ArithmeticException
if the value is out of range.
Code Block | ||
---|---|---|
| ||
class CastAway { public static void workWith(int i) { // check if i is within byte range if ((i < Byte.MIN_VALUE) || (i > Byte.MAX_VALUE)) { throw new ArithmeticException("Value is out of range"); } byte b = (byte) i; // work with b } } |
The following code example demonstrates how to perform explicit narrowing from a long
to an int
where range-checking is not required Alternatively, the workWith()
method can explicitly narrow when the programmer's intent is to truncate the value.
Code Block | ||
---|---|---|
| ||
long value = /* initialize */; int iclass CastAway { public static void workWith(int i) { byte b = (intbyte) (valuei % 0x100000000L); 0x10000L; // 2^8; // 2^32 work with b } } |
The rangeRange-checking is unnecessary because the truncation that is normally implicit in a narrowing conversion is made explicit. The compiler will optimize the operation away, and for that reason, no performance penalty is incurred. Similar operations may be used for converting to other integral types.
...