Java Math.addExact
Add integers with an explicit overflow check.
A simple example
Math.addExact
- Start with 2 and 3
- Do this Add the integers
- Result 5
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.addExact(2, 3));
}
}
5
Syntax
Math.addExact(stock, shipment)
JDK 21 method signatures (2)
public static int addExact(int x, int y)
public static long addExact(long x, long y)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaAdd a shipment to the stock count
A delivery reaches the stockroom while the existing count is still on the books. Before recording the new total, the clerk needs arithmetic that can represent the incoming shipment without silently changing the count.
class Main {
public static void main(String[] args) throws Exception {
int stock = 90;
int shipment = 12;
System.out.println(Math.addExact(stock, shipment));
}
}
102
Receiving twelve items increases stock from ninety to 102.
Restock the workshop shelf
A tutor counts 35 components on the shelf. A delivery adds another 18, and the register must show the new total.
Using 35 · 18 gives 53 items for this measurement.
Combine returned library kits
The morning collection contains 24 kits. Eleven more come back at lunch and the librarian adds the two batches.
Using 24 · 11 gives 35 items for this measurement.
What to watch for
An out-of-range integer result raises ArithmeticException. Decide how the caller should handle that failure.