Casting a user-controlled numeric value to a narrower type can result in truncated values unless the input is validated.

Narrowing conversions may cause potentially unintended results. For example, casting the positive integer value 128 to type byte yields the negative value -128.

Guard against unexpected truncation of user-controlled arithmetic data by doing one of the following:

In this example, a value is read from standard input into a long. Because the value is a user-controlled value, it could be extremely large. Casting this value to a narrower type could therefore cause unexpected truncation. The scaled2 example uses a guard to avoid this problem and checks the range of the input before performing the cast. If the value is too large to cast to type int it is rejected as invalid.

  • The CERT Oracle Secure Coding Standard for Java: NUM12-J. Ensure conversions of numeric types to narrower types do not result in lost or misinterpreted data.