Java Integer Overflow: Why Adding Positive Numbers Gives a Negative Sum
Have you ever summed a list of positive int values in Java and suddenly got a negative number—with no exception and no compiler warning?
This happens because Java's 32-bit int overflows silently. Below is a minimal counterexample, why it fails, and the two clean ways to fix it.
1. The Counterexample (Passes Small Tests, Fails Large Inputs)
With small sample numbers like 100 and 200, this code looks completely fine. Pass two large positive values—such as 1,500,000,000 each—and the result turns negative:
public class OverflowDemo {
public static void main(String[] args) {
int[] values = {1_500_000_000, 1_500_000_000};
int sum = 0;
for (int x : values) {
sum += x;
}
System.out.println("Sum = " + sum);
}
}
Actual Output:
Sum = -1294967296
2. Why Does This Happen?
A Java int is a signed 32-bit integer whose maximum value is 2,147,483,647 (Integer.MAX_VALUE). When the running total crosses that limit, Java wraps around to the negative range instead of throwing an error.
| Type | Size | Max Value | Behavior on Overflow |
|---|---|---|---|
int | 32-bit | 2,147,483,647 | Wraps silently to negative |
long | 64-bit | 9,223,372,036,854,775,807 | Safe for large sums (wraps if exceeded) |
3. Common Trap: Casting AFTER Addition
// STILL WRONG: overflow happens inside (a + b) BEFORE casting to long
long bad = (long) (1_500_000_000 + 1_500_000_000);
System.out.println(bad); // -1294967296
4. The Right Fix: Accumulate in long (or Fail Fast with Math.addExact)
public class OverflowFixed {
public static void main(String[] args) {
int[] values = {1_500_000_000, 1_500_000_000};
long sum = 0L;
for (int x : values) {
sum += x; // promoted to long before addition
}
System.out.println("Sum = " + sum);
}
}
Output:
Sum = 3000000000
If you want Java to throw an ArithmeticException instead of wrapping silently, use Math.addExact():
int safeSum = Math.addExact(1_500_000_000, 1_500_000_000);
// Throws java.lang.ArithmeticException: integer overflow
Summary Checklist
- Never assume a sum of
intvalues fits inside anint. - Start the accumulator as
long sum = 0L;before the loop. - Use
Math.addExact()when silent wrap-around would corrupt business or financial data.
Comments
Post a Comment