...
Integer type ranges are defined by the JLS, §4.2.1, "Integral Types and Values", [JLS 2005] and are also described in rule " NUM00-J. Detect or prevent integer overflow."
The table below presents the rules for narrowing primitive conversions of integer types. In the table, for an integer type T
, n
represents the number of bits used to represent the resulting type T
(precision).
...
Note that conversions from float
to double
or double
to float
can also lose information about the overall magnitude of the converted value. See rule "NUM06-J. Use the strictfp modifier for floating-point calculation consistency across platforms" for additional information.
...
Code Block | ||
---|---|---|
| ||
double i = Double.MIN_VALUE; double j = Double.MAX_VALUE; if ((i < Float.MIN_VALUE) || (i > Float.MAX_VALUE) || (j < Float.MIN_VALUE) || (j > Float.MAX_VALUE)) { throw new ArithmeticException ("Value is out of range"); } float b = (float) i; float c = (float) j; //other operations |
Exceptions
NUM12-EX0: Java's narrowing conversions are both well-defined and portable; knowledgeable programmers can intentionally apply such conversions in contexts where their output is both expected and reasonable. Consequently, narrowing conversions are permitted when the code contains comments that document both the use of narrowing conversions and that the potential for truncation has been anticipated. A suitable comment might read: "// Deliberate narrowing cast of i; possible truncation OK"
...
INT31-C. Ensure that integer conversions do not result in lost or misinterpreted data | ||||
| FLP34-C. Ensure that floating point conversions are within range of the new type | |||
INT31-CPP. Ensure that integer conversions do not result in lost or misinterpreted data | ||||
| FLP34-CPP. Ensure that floating point conversions are within range of the new type | |||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="afd813ce1f5c77d9-209c9795-4c594212-97c3be65-ff9ec1d14d6e1a1233850ce3"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | "Numeric Conversion Errors [FLC]" | ]]></ac:plain-text-body></ac:structured-macro> |
CWE ID 681, "Incorrect Conversion between Numeric Types" | ||||
| CWE ID 197, "Numeric Truncation Error" |
...