...
Code Block | ||
---|---|---|
| ||
public static int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException { return safeAdd(oldAcc, safeMultiply(newVal, scale)); } |
Compliant Solution (Java 8, Math.*exact()
)
This compliant solution uses the addExact()
and multiplyExact()
methods defined in the Math
class. These methods were added to Java as part of the Java 8 release, and they also either return a mathematically correct value or throw ArithmeticException
. The Math
class also provides SubtractExact()
and negateExact()
, but does not provide any methods for safe division or absolute value.
Code Block | ||
---|---|---|
| ||
public static int multAccum(int oldAcc, int newVal, int scale)
throws ArithmeticException {
return Math.addExact(oldAcc, Math.multiplyExact(newVal, scale));
} |
Compliant Solution (Upcasting)
This compliant solution shows the implementation of a method for checking whether a value of type long
falls within the representable range of an int
using the upcasting technique. The implementations of range checks for the smaller primitive integer types are similar.
...