.addExact()
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
.
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.javapublic 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 isLong.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:
784Exception in thread "main" java.lang.ArithmeticException: long overflowat java.base/java.lang.Math.addExact(Math.java:845)at Main.main(Main.java:13)
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.