...
Code Block | ||
---|---|---|
| ||
public static long intRangeCheck(long value) throws ArithmeticException { if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) { throw new ArithmeticException("Integer overflow"); } return value; } public static int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException { final long res = intRangeCheck( ((long) oldAcc) + intRangeCheck((long) newVal * (long) scale) ); return (int) res; // Safe down-castdowncast } |
Note that this approach cannot be applied to values of type long
because long
is the largest primitive integral type. Use the BigInteger
technique instead when the original variables are of type long
.
...
Code Block | ||
---|---|---|
| ||
private static final BigInteger bigMaxInt = BigInteger.valueOf(Integer.MAX_VALUE); private static final BigInteger bigMinInt = BigInteger.valueOf(Integer.MIN_VALUE); public static BigInteger intRangeCheck(BigInteger val) throws ArithmeticException { if (val.compareTo(bigMaxInt) == 1 || val.compareTo(bigMinInt) == -1) { throw new ArithmeticException("Integer overflow"); } return val; } public static int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException { BigInteger product = BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale)); BigInteger res = intRangeCheck(BigInteger.valueOf(oldAcc).add(product)); return res.intValue(); // safeSafe conversion } |
Noncompliant Code Example (AtomicInteger
)
...
[API 2006] | Class |
Puzzle 27, "Shifty i's" | |
[Bloch 2008] | Item 12, "Minimize the Accessibility of Classes and Members" |
[JLS 2005] | §4.2.2, "Integer Operations" |
Chapter 5, "Integers" | |
[Seacord 2015] | IDS17-J. Prevent XML External Entity Attacks LiveLesson |
"Primitive Data Types" |
...