Detect overflow before recording a total in Java

Adding one to the largest int exceeds its range. Use addExact to make overflow an explicit outcome that the caller can handle.

A simple example

Use checked addition

  1. Start with 2 and 1
  2. Do this Use checked addition
  3. Result 3
The small sum fits in an int.

Apply it to a real problem

  1. Start with Counters at 41 and at the integer limit
  2. Do this Try to register one more item
  3. Result 42 or capacity exceeded
The checked operation prevents an overflowing counter from wrapping around.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
public class Main {
    public static void main(String[] args) throws Exception {
        for (int current : new int[]{41, Integer.MAX_VALUE}) {
            try {
                System.out.println(Math.addExact(current, 1));
            } catch (ArithmeticException overflow) {
                System.out.println("capacity exceeded");
            }
        }
    }
}
Output
42
capacity exceeded

Official Java documentation