Java Tutorial Java Advanced Java References

Java Math - addExact() Method



The Java addExact() method returns sum of its arguments. The method can be overloaded and it can take int and long arguments. It throws an exception, if the result overflows an int or a long.

Syntax

public static int addExact(int x, int y)  
public static long addExact(long x, long y)  

Parameters

x Specify the first value.
y Specify the second value.

Return Value

Returns sum of its arguments.

Exception

Throws ArithmeticException, if the result overflows an int or a long.

Example:

In the example below, addExact() method is used to add given numbers.

public class MyClass {
 public static void main(String[] args) {
  int x = 12, y = 17;
  long p = 145, q = 139;
  System.out.println(Math.addExact(x, y)); 
  System.out.println(Math.addExact(p, q));    
 }
}

The output of the above code will be:

29
284

❮ Java Math Methods