...
This compliant solution range-checks both the i and j variables before converting to the resulting integer type. Because both values are the maximum value is out of the valid range for a short, this code will always throw an ArithmeticException.
...
Casting a numeric value to a narrower type can result in information loss related to the sign and magnitude of the numeric value. As a result, data can be misrepresented or interpreted incorrectly.
Rule | Severity | Likelihood | Detectable | RepairableRemediation Cost | Priority | Level |
|---|---|---|---|---|---|---|
NUM12-J | Low | Unlikely | Yes | YesMedium | P2P3 | L3 |
Automated Detection
Automated detection of narrowing conversions on integral types is straightforward. Determining whether such conversions correctly reflect the intent of the programmer is infeasible in the general case. Heuristic warnings could be useful.
| Tool | Version | Checker | Description | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| CodeSonar |
| JAVA.MATH.APPROX.E | Approximate e Constant | (Java)
| (Java)
| (Java)
| (Java)|||||||
| Parasoft Jtest |
| CERT.NUM12.CLP | Do not cast primitive data types to lower precision | ||||||||||
| PVS-Studio |
| V6124 |
Related Guidelines
INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data | |
| ISO/IEC TR 24772:2010 | Numeric Conversion Errors [FLC] |
CWE-681, Incorrect Conversion between Numeric Types |
...