Codectionary / Developer documentation / Java

Detecting Integer Overflow with Math.addExact

Detect arithmetic overflow explicitly instead of accepting a wrapped integer result.

What it is and why to use it

An int has a fixed range. Ordinary integer addition can wrap when the mathematical result falls outside that range; it does not automatically throw. Math.addExact provides checked addition, throwing ArithmeticException when the result cannot fit in the chosen int or long type.

How it works

The first operation below has a representable result and returns normally. The second attempts to add one to Integer.MAX_VALUE, so it throws before assigning a result. Catching that specific exception allows this small program to show a controlled message.

Common mistakes and limitations

Checking addition does not check earlier multiplications or conversions. Use the matching exact operation at each relevant step. long has a wider but still finite range; BigInteger is appropriate when arbitrary-precision integer arithmetic is required.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

int total = Math.addExact(first, second);

Examples

Detecting Integer Overflow with Math.addExact

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  public static void main(String[] args) {
    System.out.println(Math.addExact(20, 30));
    try {
      System.out.println(Math.addExact(Integer.MAX_VALUE, 1));
    } catch (ArithmeticException error) {
      System.out.println("Total is too large");
    }
  }
}
  1. 20 + 30 fits in int, so the first call prints 50.
  2. Integer.MAX_VALUE is the largest int; adding one cannot be represented and addExact throws.
  3. The catch block prints a clear message rather than using a wrapped result. This is useful when counters or totals must fail explicitly on overflow.
  4. Expected output: 50 Total is too large

Best practices

  • Choose an overflow policy deliberately.
  • Test maximum, minimum and boundary values.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading