Overflow and big numbers
24 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Java's primitive int and long operators (+, -, *) never throw an exception on overflow — they silently wrap around in two's complement arithmetic and produce wrong answers that pass small sample tests and fail hidden large constraints.
int and long Limits and Silent Wrap-Around
Memorize the exact order of magnitude of Java's two main integer types so you can read problem constraints at a glance.
Example 1 · Silent int Overflow vs Casting to long First
public class IntAndLongLimitsDemo { public static void main(String[] args) { int maxInt = Integer.MAX_VALUE; System.out.println("Integer.MAX_VALUE + 1 = " + (maxInt + 1)); System.out.println("Math.abs(MIN_VALUE) = " + Math.abs(Integer.MIN_VALUE));
int width = 100_000; int height = 100_000; long brokenArea = width * height; // overflows int first! long correctArea = (long) width * height; // widens to long before * System.out.println("brokenArea = " + brokenArea); System.out.println("correctArea = " + correctArea); }}Integer.MAX_VALUE + 1 = -2147483648 Math.abs(MIN_VALUE) = -2147483648 brokenArea = 1410065408 correctArea = 10000000000
What this code does
100_000 * 100_000is 10¹⁰, which wraps around modulo 2³² to1_410_065_408when evaluated in 32-bitint.- Casting the left operand
(long) widthpromotes the multiplication itself to 64-bitlong.
Integer.MAX_VALUE + 1wraps around toInteger.MIN_VALUE(-2_147_483_648).Math.abs(Integer.MIN_VALUE)returnsInteger.MIN_VALUE(still negative!) because +2³¹ cannot fit in a signed 32-bitint.- Rule of thumb from constraints: if an intermediate value can exceed 2 × 10⁹, use
long; if it can exceed 9 × 10¹⁸ (and no modulus is given), useBigInteger. int(32-bit signed): range -2³¹ (-2_147_483_648) to 2³¹ - 1 (2_147_483_647≈ 2.14 × 10⁹, roughly 9–10 decimal digits).long(64-bit signed): range -2⁶³ to 2⁶³ - 1 (9_223_372_036_854_775_807L≈ 9.22 × 10¹⁸, roughly 18–19 decimal digits). Whenever a sum of n = 10⁵ elements where each element is up to 10⁵ is accumulated, the maximum sum is 10¹⁰ > 2.14 × 10⁹, which overflowsintand requireslong. Watch out for the type-promotion trap: inlong area = width * height;, ifwidthandheightare bothint, Java multiplies them as a 32-bitintfirst (overflowing!) and only then widens the corrupted result tolong. Cast the first operand:long area = (long) width * height;.
Predict the output
Predict the overflow
Read each program and pick what it prints.
Round 1 of 3
Square 100 000 as an int.
Math.addExact, Math.multiplyExact, and Pre-Check Guards
Since Java 8, java.lang.Math provides exact arithmetic methods that throw ArithmeticException("integer overflow") the moment a calculation exceeds the type's bounds: Math.addExact(a, b), Math.subtractExact(a, b), Math.multiplyExact(a, b), Math.negateExact(a), and Math.toIntExact(longVal).
Example 2 · Detecting Overflow with Math.addExact, Math.multiplyExact, and Pre-Checks
public class ExactMathAndPrecheckDemo { public static boolean willMultiplyOverflow(long a, long b) { if (a == 0 || b == 0) return false; return a > Long.MAX_VALUE / b; }
public static void main(String[] args) { try { int sum = Math.addExact(1_500_000_000, 1_000_000_000); System.out.println(sum); } catch (ArithmeticException ex) { System.out.println("Caught addExact overflow: " + ex.getMessage()); }
try { long prod = Math.multiplyExact(100_000L, 200_000L); System.out.println("Safe multiplyExact: " + prod); } catch (ArithmeticException ex) { System.out.println("Caught multiplyExact overflow"); }
System.out.println("Will 10^10 * 10^8 overflow long? " + willMultiplyOverflow(10_000_000_000L, 100_000_000L)); System.out.println("Will 10^10 * 10^9 overflow long? " + willMultiplyOverflow(10_000_000_000L, 1_000_000_000L)); }}Caught addExact overflow: integer overflow Safe multiplyExact: 20000000000 Will 10^10 * 10^8 overflow long? false Will 10^10 * 10^9 overflow long? true
What this code does
Math.addExactandMath.multiplyExactfail fast with anArithmeticExceptioninstead of silently returning a corrupted negative number.- For positive
a, b,a > Long.MAX_VALUE / btests whethera * b > Long.MAX_VALUEwithout ever executing the overflowing multiplication.
Math.addExact(x, y)andMath.multiplyExact(x, y)have overloads for both(int, int)and(long, long).Math.toIntExact(longVal)safely narrows alongtointor throwsArithmeticExceptionif out of 32-bit range.- Pre-check before
acc = acc * 10 + digit(foracc >= 0):if (acc > (Integer.MAX_VALUE - digit) / 10)-> overflow!
When a problem asks you to clamp or return 0 on 32-bit overflow (such as Reverse Integer or String to Integer atoi) without using long or catching exceptions, rearrange the inequality so the check itself cannot overflow: to test if a + b > Integer.MAX_VALUE for positive a, b, check a > Integer.MAX_VALUE - b; to test if a * b > Integer.MAX_VALUE, check a > Integer.MAX_VALUE / b.
BigInteger When long Is Not Enough
When a problem requires exact arithmetic beyond 9.22 × 10¹⁸ — such as computing 100! in full decimal digits, adding 500-digit numbers, or multiplying two 64-bit long values modulo a 60-bit number — use java.math.BigInteger.
Example 3 · Exact 30! and Huge Modular Arithmetic with BigInteger
import java.math.BigInteger;
public class BigIntegerDemo { public static BigInteger exactFactorial(int n) { BigInteger result = BigInteger.ONE; for (int i = 2; i <= n; i++) { result = result.multiply(BigInteger.valueOf(i)); } return result; }
public static void main(String[] args) { BigInteger f30 = exactFactorial(30); System.out.println("30! = " + f30); System.out.println("Digits in 30! = " + f30.toString().length());
BigInteger a = new BigInteger("9000000000000000000"); BigInteger b = new BigInteger("8000000000000000000"); BigInteger mod = new BigInteger("10000000000000000003"); System.out.println("(a * b) mod 10^19+3 = " + a.multiply(b).mod(mod)); }}30! = 265252859812191058636308480000000 Digits in 30! = 33 (a * b) mod 10^19+3 = 8400000000000000009
What this code does
30!has 33 decimal digits (far aboveLong.MAX_VALUE's 19 digits), whichBigIntegercomputes exactly.- Notice
result = result.multiply(...): becauseBigIntegeris immutable, ignoring the return value leavesresultunchanged.
A BigInteger is an immutable object that stores an arbitrary-length array of 32-bit words on the heap.
Because BigInteger is immutable, methods like a.add(b) or a.multiply(b) do not modify a; they return a brand-new BigInteger instance. Creating heap objects inside a tight loop of 10⁶ iterations is 10×–50× slower than primitive long operations, so only reach for BigInteger when values genuinely exceed 64 bits.
- Create from a
long:BigInteger.valueOf(42L). Create from a decimal string:new BigInteger("9999999999999999999999999"). - Built-in constants:
BigInteger.ZERO,BigInteger.ONE,BigInteger.TWO(added in Java 9),BigInteger.TEN. - Core methods:
.add(b),.subtract(b),.multiply(b),.divide(b),.mod(b),.gcd(b),.modPow(exp, mod),.compareTo(b).
Next step
Check your understanding
10 quick questions