How to detect integer overflow
Short answer
Ordinary operations silently wrap the result around the limit. The Math.addExact(), multiplyExact() and similar methods throw an exception instead:
void main() {
int max = Integer.MAX_VALUE;
IO.println(max + 1);
IO.println(Math.addExact(max, 1));
}Output:
-2147483648
Exception in thread "main" java.lang.ArithmeticException: integer overflowCatching overflow
Catch ArithmeticException to handle the situation:
void main() {
int items = 70_000;
int price = 40_000;
try {
IO.println(Math.multiplyExact(items, price));
} catch (ArithmeticException e) {
IO.println("Too large: " + e.getMessage());
}
}Output:
Too large: integer overflowCalculating in long
Often it is enough to do the calculation in long. Cast at least one operand to long before multiplying:
void main() {
int items = 70_000;
int price = 40_000;
long total = (long) items * price;
IO.println(total);
}Output:
2800000000Common mistake
Casting the result to long. The multiplication was done in int and overflowed before the value got into the long:
void main() {
int items = 70_000;
int price = 40_000;
long wrong = (long) (items * price);
IO.println(wrong);
}Output:
-1494967296Functions used in this recipe
- ArithmeticException — Thrown on an invalid arithmetic operation, such as integer division by zero.
- Integer.MAX_VALUE — The largest int value; its partner is Integer.MIN_VALUE.