Java .addExact()

shlokPrajapati6005371709's avatar
Published Oct 23, 2022

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

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

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.

Example

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:

784
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

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours