Java Reference ยท Operators
Integer overflow in Java
Reference for integer overflow in Java: silent two's complement wrapping, detecting it with the exact arithmetic methods, and safe alternatives.
Java integer arithmetic never throws on overflow. When the result of an int or long operation does not fit, the extra high bits are discarded and the value wraps around in two's complement: Integer.MAX_VALUE + 1 is Integer.MIN_VALUE. This applies to +, -, *, unary minus, ++, -- and shifts, and also to byte, short and char once they are narrowed back.
The standard library provides exact versions of the common operations in Math that throw ArithmeticException instead of wrapping. Use them whenever a wrong silent result would be worse than an exception.
int x = Integer.MAX_VALUE; x + 1; // -2147483648 Math.addExact(x, 1); // throws ArithmeticException
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
Math.addExact(int x, int y) // also long Math.subtractExact(int x, int y) Math.multiplyExact(int x, int y) // also (long, int) and long Math.incrementExact(int a) Math.decrementExact(int a) Math.negateExact(int a) Math.toIntExact(long value) Math.absExact(int a) // since Java 15
| Method | Throws ArithmeticException when |
|---|---|
addExact, subtractExact, multiplyExact |
the result does not fit the type |
incrementExact, decrementExact, negateExact |
the result does not fit (e.g. MIN_VALUE negated) |
toIntExact |
the long is outside the int range |
absExact |
the argument is MIN_VALUE |
Also available: Math.multiplyHigh, Math.floorDiv, Math.ceilDiv (Java 18) and Math.clamp (Java 21).
Usage notes
- Cast early. In
(long) a * bthe cast makes the multiplication happen inlong. In(long) (a * b)it happens too late. Likewise write24L * 60 * 60 * 1000. Integer.MIN_VALUEis special: it has no positive counterpart, so-xandMath.abs(x)return it unchanged.- Averaging and binary search:
(lo + hi) / 2can overflow. Uselo + (hi - lo) / 2or(lo + hi) >>> 1. - Floating point never overflows silently: it becomes
Infinity. Integer division by zero throws;x / 0.0gives infinity. - Exact methods are intrinsics and nearly as fast as plain arithmetic, but they are method calls; do not wrap every addition, only where bad input can reach.
- For unlimited size use
BigInteger. For unsigned semantics seeInteger.toUnsignedString,Integer.divideUnsignedandInteger.compareUnsigned. - Hash codes and checksums rely on wrapping on purpose.