Integer Overflow Protection & Math.addExact()
1Concept
In financial and safety-critical banking systems, silent integer overflow wrapping (-2147483648) can cause severe calculation bugs. Java 8 introduced Math.addExact(), Math.subtractExact(), Math.multiplyExact(), and Math.toIntExact() which perform exact arithmetic and throw a java.lang.ArithmeticException immediately upon overflow.
2Architecture Diagram
Normal Int Arithmetic: Integer.MAX_VALUE + 1 ---> Wraps around to -2147483648 (Silent Data Corruption!) Math.addExact Arithmetic: Integer.MAX_VALUE + 1 ---> Throws java.lang.ArithmeticException: integer overflow
3Code Example
Core Java
public class SafeArithmeticDemo {
public static void main(String[] args) {
int balance = Integer.MAX_VALUE - 10;
int deposit = 50;
try {
System.out.println("Attempting safe deposit addition...");
int newBalance = Math.addExact(balance, deposit);
System.out.println("New Balance: " + newBalance);
} catch (ArithmeticException e) {
System.err.println("ALERT: " + e.getMessage() + "! Transaction rejected due to Overflow.");
}
}
}4Expected Output
Attempting safe deposit addition... ALERT: integer overflow! Transaction rejected due to Overflow.
5Key Takeaways
- ✓Always use Math.addExact() or Math.multiplyExact() when processing financial transactions.
- ✓Math.toIntExact(longVal) safely casts a 64-bit long to 32-bit int with overflow checking.
- ✓ArithmeticException is an unchecked RuntimeException.