Java Math addExact() Method
Example
Add integers:
System.out.println(Math.addExact(12, 16));
System.out.println(Math.addExact(10000, 24060));
Try it Yourself »
Definition and Usage
The addExact()
method adds two integers and throws an exception if the addition causes an overflow. This prevents incorrect results that can occur from adding really large numbers.
Syntax
One of the following:
public static int addExact(int x, int y)
public static long addExact(long x, long y)
Parameter Values
Parameter | Description |
---|---|
x | Required. The first number to be added. |
y | Required. The second number to be added. |
Technical Details
Returns: | An int or long value representing the sum of two numbers. |
---|---|
Throws: | ArithmeticException - If the sum causes an overflow. |
Java version: | 1.8+ |
❮ Math Methods