How does Java handle integer overflow?
In Java, integer overflow occurs when a calculation exceeds the range of the data type. Java handles it by wrapping around to the other end of the range:
- For int (32-bit): Range is -2,147,483,648 to 2,147,483,647. If a value exceeds this, it wraps around. Example:
int x = Integer.MAX_VALUE + 1; // x becomes Integer.MIN_VALUE
- Java doesn’t throw an exception for overflow in primitive types. Use
Math.addExact()
orMath.multiplyExact()
to detect overflow and throw an exception.
In short: Java wraps around on overflow unless you explicitly check for it.