Video in progress

Junior ☕ Core Java

What happens when an int value goes past its limit (overflow)?

No exception is thrown: the value silently "wraps around" to a negative (or the opposite) number. For example, Integer.MAX_VALUE + 1 equals Integer.MIN_VALUE. For important calculations, use Math.addExact or a long.

📖 Answer

int max = Integer.MAX_VALUE;      // 2 147 483 647
System.out.println(max + 1);      // -2147483648

Common cases in practice:

  • milliseconds: int days = 30; int ms = days * 24 * 60 * 60 * 1000; goes past 2.5 billion, and the result is negative. The right way: 30L * 24 * 60 * 60 * 1000 or Duration.ofDays(30).toMillis().
  • computing the midpoint: (low + high) / 2 overflows with large indexes. The safe forms: low + (high - low) / 2 or (low + high) >>> 1.
  • money in cents: large amounts don't fit in an int.

To catch the error:

Math.addExact(a, b);      // ArithmeticException on overflow
Math.multiplyExact(a, b);
Math.toIntExact(longValue);

A long isn't unlimited either (about 9.2 × 10^18). If you need even more, use BigInteger.