Published Oct 23, 2022
Contribute to Docs

The Math.addExact() method returns the sum of its arguments. It will throw an exception if the result overflows either int or long.


Math.addExact(a, b)

Both parameters a and b must either be of type int or long.

An exception is thrown if either parameter is equal to Integer.MAX_VALUE, Long.MAX_VALUE, or the result exceeds type int or long.


This following example returns the sum of two values with the .addExact() method:

// Main.java
public class Main {
public static void main(String[] args) {
int a = 575;
int b = 209;
System.out.println(Math.addExact(a, b));
Overflow will occur if any one of the argument is
Long.MAX_VALUE or Integer.MAX_VALUE.
long x = Long.MAX_VALUE;
long y = 86712;
System.out.println(Math.addExact(x, y));

This will produce the following output:

Exception in thread "main" java.lang.ArithmeticException: long overflow
at java.base/java.lang.Math.addExact(Math.java:845)
at Main.main(Main.java:13)

All contributors

Looking to contribute?

Learn Java on Codecademy