liveBook · Manning

Math.addExact

As explained in 100 Java Mistakes and How to Avoid Them

Math.addExact is a Java static method that returns an exact integer sum and throws ArithmeticException when the sum overflows.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains overflow signaling, JIT treatment, readability trade-offs, and composition with exact multiplication.
Examples
Uses string-replacement buffer sizing guarded by Math.addExact and Math.multiplyExact.
What it assumes
Assumes familiarity with Java integer arithmetic and exception handling.
What you can do after
Apply it via Math.addExact to detect overflow and handle arithmetic failure before using a derived value.
How it connects
Connects integer overflow with ArithmeticException, Math.multiplyExact, JIT compilation, and OutOfMemoryError.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.