The syntax of the addExact() method is:
Math.addExact(num1, num2)
Here, addExact() is a static method. Hence, we are accessing the method using the class name, Math.
addExact() Parameters
The addExact() method takes two parameters.
- num1 - value that is added to num2
- num2 - value that is added to num1
Note: The data type of both values should be either int or long.
addExact() Return Value
- returns the sum of two values
Example 1: Java Math addExact()
In the above example, we have used the Math.addExact() method with the int and long variables to calculate the sum.
The addExact() method throws an exception if the result of addition overflows the data type. That is, the result should be within the range of the data type of specified variables.
In the above example, the value of a is the maximum int value and the value of b is 1. When we add a and b,
2147483647 + 1
=> 2147483648 // out of range of int type
Hence, the addExact() method throws the integer overflow exception.