Math.addExact()
Adds two numbers and throws ArithmeticException on overflow. See also multiplyExact() and toIntExact().
Available since: Java 8
Syntax
public static int addExact(int x, int y)Parameters
| Parameter | Type | Description |
|---|---|---|
| x | int, long | The first addend. |
| y | same type as x | The second addend. |
Return value
same type as xThe sum, if it fits in the type.
Examples
The plain + silently overflows, addExact() reports an error:
void main() {
int big = Integer.MAX_VALUE;
IO.println(big + 1);
IO.println(Math.addExact(big, 1));
}Output:
-2147483648
Exception in thread "main" java.lang.ArithmeticException: integer overflowtoIntExact() safely turns a long into an int:
void main() {
long small = 1_000L;
long huge = 5_000_000_000L;
IO.println(Math.toIntExact(small));
try {
Math.toIntExact(huge);
} catch (ArithmeticException e) {
IO.println("Error: " + e.getMessage());
}
}Output:
1000
Error: integer overflowNotes
The family: addExact(), subtractExact(), multiplyExact(), incrementExact(), negateExact(), toIntExact(). They are for places where overflow means bad data: money, counters, sizes. If the numbers really can be huge, use BigInteger or BigDecimal.
See also
- Integer.MAX_VALUE — The largest int value; its partner is Integer.MIN_VALUE.
- ArithmeticException — Thrown on an invalid arithmetic operation, such as integer division by zero.
- BigInteger — An integer of any size — for when even long is not enough.
- Long.parseLong() — Converts a string with an integer to a long — for numbers that do not fit in an int.
In the tutorial
- Primitive types — Java's eight primitive types: int, long, double, float, char, boolean, byte and short, their ranges and overflow.