Java Math addExact() Method
The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int.
Syntax
public static int addExact (int x, int y)
public static long addExact (long x, long y)
Parameters
x= first value
y= second value
Return Value
The addExact () method returns the sum of the arguments.
Throws
The addExact() method throws:
ArithmeticException- if the result overflows an int or a long
Example 1:
public class JavaMathAddExactExample1 { public static void main(String[] args) { //returns the sum of the arguments. int x=-23; int y=123; System.out.println("Sum : "+ Math.addExact(x,y)); } }
Output:
Sum : 100
Example 2:
public class JavaMathAddExactExample2 { public static void main(String[] args) { int x=-109; int y=109; System.out.println("Sum : "+ Math.addExact(x,y)); } }
Output:
Sum : 0
Example 3:
public class JavaMathAddExactExample3 { public static void main(String[] args) { int x=Integer.MAX_VALUE; int y=Integer.MIN_VALUE; System.out.println("Sum : "); System.out.print(x+"+"+"("+y+") = "); System.out.println(Math.addExact(x,y)); } }
Output:
Sum : 2147483647+(-2147483648) = -1
Example 4:
public class JavaMathAddExactExample4 { public static void main(String[] args) { long x=95444353546386l; long y=Long.MAX_VALUE; System.out.println(Math.addExact(x,y)); } }
Output:
Exception in thread "main" java.lang.ArithmeticException: long overflow at java.lang.Math.addExact(Math.java:809) at com.TutorialsAndExamples.JavaMathAddExactExample4.main(JavaMathAddExactExample4.java:7)