Math.addExact(x, y) adds integer values without silent wraparound: it throws ArithmeticException if the sum overflows. Use it where an incorrect size, count, or other derived value would be worse than a handled failure. When no overflow occurs, JIT replacement is expected to make it comparable to ordinary addition. section 4.2.1
Guard a computed buffer size
A replacement operation can overflow while calculating a result length. Combine Math.addExact with Math.multiplyExact, then translate ArithmeticException into the failure appropriate for allocation. section 4.2.1
int bufferSize;
try {
bufferSize = Math.addExact(str.length(),
Math.multiplyExact(
replacement.length() - target.length(),
replacementCount));
} catch (ArithmeticException e) {
throw new OutOfMemoryError();
}
This guarded calculation catches overflow before a wrapped buffer size is used. section 4.2.1
Use it deliberately:
- Prefer it over + when overflow must be detected rather than allowed to produce a corrupted value. section 4.2.1
- Catch ArithmeticException only where the caller can make a meaningful recovery or map it to the required failure. section 4.2.1
- Accept the readability trade-off; Java cannot redefine + to mean checked addition. section 4.2.1
