Integer Range and Overflow
Why an int can only hold values between two limits, what Integer.MAX_VALUE and Integer.MIN_VALUE are, what happens when a calculation goes past them, and how to recognize and avoid integer overflow.
Integer values in Java are represented by values of type int, which are stored using a finite amount of memory: 4 bytes. Therefore an int must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE, inclusive, roughly minus 2.1 billion to plus 2.1 billion. If an expression would evaluate to an int value outside that range, an integer overflow occurs. The result is an int value in the allowed range, but not necessarily the value expected, and no error message warns you.
1A Finite Box for Every int
In mathematics, integers go on forever. In a computer, every value must fit in a fixed amount of memory. Java stores each int in 4 bytes, which is 32 bits (binary digits). With 32 bits there are 232, about 4.29 billion, different patterns, and Java uses them to represent about half negative numbers and half zero-or-positive numbers.
That design choice has a consequence: there is a largest int and a smallest one. Most of the time this does not matter, since everyday counts such as students, points, or days are far smaller than two billion. But some quantities, such as milliseconds over long periods, populations of countries, or products of large numbers, can exceed the limit, and a program that ignores the limit can produce absurd answers without any warning.
2Integer.MAX_VALUE and Integer.MIN_VALUE
Java provides two named constants for the limits. The constant Integer.MAX_VALUE holds the value of the largest possible int, 2,147,483,647. The constant Integer.MIN_VALUE holds the smallest possible int, −2,147,483,648. Notice that the negative limit is one larger in size than the positive limit, because zero takes one of the non-negative patterns.
Using the constants is better than typing the numbers: they are easy to read and impossible to mistype. They are also useful as starting values. A program looking for the smallest value in a set of data can start its "smallest so far" variable at Integer.MAX_VALUE, guaranteeing that the first real value it sees will be smaller.
int holds values from Integer.MIN_VALUE to Integer.MAX_VALUE, inclusive. Going past either end wraps around to the other end.| Constant or fact | Value | Meaning |
|---|---|---|
Integer.MAX_VALUE | 2,147,483,647 | The largest possible int value |
Integer.MIN_VALUE | −2,147,483,648 | The smallest possible int value |
| Storage for an int | 4 bytes (32 bits) | A finite amount of memory, so a finite range |
Integer.MAX_VALUE + 1 | −2,147,483,648 | Overflow wraps to the minimum |
Integer.MIN_VALUE - 1 | 2,147,483,647 | Overflow wraps to the maximum |
Printing the Range and Stepping Past It
Predict the output.
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
int big = Integer.MAX_VALUE;
big = big + 1;
System.out.println(big);
int small = Integer.MIN_VALUE;
small = small - 1;
System.out.println(small);
2147483647
-2147483648
-2147483648
2147483647
- 1The constants.
Integer.MAX_VALUEis 2,147,483,647 andInteger.MIN_VALUEis −2,147,483,648. - 2One past the maximum. Adding 1 to the largest
intoverflows and wraps around to the smallest. - 3One below the minimum. Subtracting 1 from the smallest
intwraps around to the largest. - 4No error message. Overflow does not stop the program or warn you; it silently produces a value in range that is not the value you expected.
int, just not the right one.3What Overflow Does
If an expression would evaluate to an int value outside the allowed range, an integer overflow occurs. Java does not stop the program or report an error. Instead, it keeps only the part of the result that fits in 32 bits, which makes the value wrap around: one more than the maximum becomes the minimum, and one less than the minimum becomes the maximum. The result is always an int in the allowed range, but not necessarily the value expected.
Overflow is a logic error: the code compiles and runs, and only the wrong answer reveals it. Its most recognizable symptom is a sign change, such as a negative result from multiplying two positive numbers or a sum that suddenly becomes negative after many additions. Any time an int result looks impossibly large, negative when it should be positive, or simply strange, consider whether a calculation went past the limit.
int, it restarts at the most negative value.When Squaring Overflows
The square root of Integer.MAX_VALUE is about 46,340.95. Predict both results.
int a = 46340;
int b = 46341;
System.out.println(a * a);
System.out.println(b * b);
2147395600
-2147479015
- 146,340². 2,147,395,600 fits below the limit, so it is correct.
- 246,341². The true value, 2,147,488,281, is larger than 2,147,483,647, so the result overflows. Java keeps only what fits in 32 bits, which happens to be −2,147,479,015.
- 3A warning sign. A negative result from multiplying two positive numbers is a classic symptom of overflow.
int.Integer overflow does not throw an exception. The program keeps running with a wrong value, which may then flow into later calculations and output. If results become negative or nonsensical once the numbers get large, suspect overflow, even though nothing crashed.
4Where Overflow Hides
Overflow most often appears in multiplication, because products grow quickly. Two numbers in the tens of thousands can already have a product beyond two billion, as squaring 46,341 shows. Chains of multiplication, such as converting years into seconds, overflow even when every individual factor is small. Repeated addition, such as a running total that grows over a long time, can also overflow eventually.
Intermediate values matter as much as final ones. In x * y / z, the multiplication happens first; if x * y overflows, dividing afterward cannot repair the damage, even when the final answer would have fit. Evaluating an expression step by step, estimating the size of each intermediate result, is the way to spot hidden overflow.
int, but the overflowed result is wildly wrong and even negative.| Quantity | Rough size | Fits in an int? |
|---|---|---|
| Students in a school | Thousands | Yes |
| Seconds in a year | About 31.5 million | Yes |
| Milliseconds in a month | About 2.6 billion | No |
| People on Earth | About 8 billion | No |
| A large city's population | Millions | Yes |
How Many Seconds in 70 Years?
A program computes the number of seconds in 70 years (ignoring leap days). Predict both results.
int seconds = 70 * 365 * 24 * 60 * 60;
System.out.println(seconds);
double secondsD = 70 * 365 * 24 * 60 * 60.0;
System.out.println(secondsD);
-2087447296
2.20752E9
- 1The int version. The true answer, 2,207,520,000, is larger than
Integer.MAX_VALUE, so the final multiplication overflows to a negative number. - 2The double version. Multiplying by
60.0makes the last step adoubleoperation. The earlier steps, ending at 36,792,000, fit comfortably in anint, so nothing overflows. - 3Scientific notation. Large
doublevalues print in E notation:2.20752E9means 2.20752 × 10⁹ = 2,207,520,000.
int result is a meaningless negative number; the double result is 2,207,520,000. Quantities in the billions need a type with a larger range.Rearranging to Stay in Range
A program computes 60,000 × 60,000 ÷ 40,000 two ways. Predict both.
int x = 60000;
int y = 60000;
int z = 40000;
System.out.println(x * y / z);
System.out.println(x / z * y);
System.out.println(x * (y / z));
-17374
60000
60000
- 1Line 1.
x * yis 3,600,000,000, which overflows before the division ever happens, giving garbage. - 2Line 2.
x / zis integer division: 60,000 ÷ 40,000 = 1. Then 1 × 60,000 = 60,000. No overflow, but the true answer is 90,000; dividing first lost the fraction. - 3Line 3. Same problem:
y / zis 1, so the result is 60,000. - 4A correct approach. Use
doublearithmetic, such as(double) x * y / z, which gives 90000.0.
int ordering is correct here, which is a signal to switch to double arithmetic.An answer of 90,000 easily fits in an int, but 60000 * 60000 / 40000 still overflows, because the intermediate product 3.6 billion does not fit. Estimate every intermediate value, not just the final one.
5Limits the Compiler Catches
The range also limits what can be written. An integer literal larger than Integer.MAX_VALUE, such as 3000000000, is not a valid int, so the compiler reports integer number too large and the program cannot run. This is different from overflow: the compiler can see that the written number is impossible, while overflow happens only when a calculation's result exceeds the range during execution.
A Literal That Is Too Large
Explain the compiler error.
int population = 8100000000;
- 1The literal itself is invalid. 8,100,000,000 is outside the
intrange, so the compiler rejects the number before the program can run. - 2Contrast with overflow. Overflow happens at run time when a calculation exceeds the range; this error happens at compile time because the written number cannot be an
intat all. - 3A workable choice. A value this large can be stored as a
double(8.1E9or8100000000.0), as long as exact whole-number precision is not essential.
int range is a compile-time error, not overflow.6Avoiding Overflow
The first defense is estimation. Before choosing int for a quantity, ask how large it could ever get. If the answer might approach billions, an int is risky. A double has a vastly larger range, so switching to double arithmetic, often by making one operand a double such as 60.0, prevents overflow, at the cost of possible round-off error in the last digits of very large values.
The second defense is ordering. When an expression multiplies and divides, the order of operations controls the size of intermediate values. Sometimes rearranging keeps every step in range; but dividing early with integers can discard fractions, so check that the rearranged version is still mathematically correct. When both risks exist, double arithmetic is usually the clearest fix.
The third defense is testing at the edges. Overflow bugs hide behind small test values: a program that multiplies two inputs works perfectly for 30 and 40 and fails for 50,000 and 50,000. When a program does arithmetic on values that could become large, include a test near the largest realistic input and check that the answer is still sensible. Printing intermediate values during that test shows exactly which step leaves the range, which tells you where a different type or a different order of operations is needed.
| Problem | When it appears | Symptom | Fix |
|---|---|---|---|
| Literal too large | Compile time | "integer number too large" | Use a double literal or rethink the units |
| Overflow in a calculation | Run time (silent) | A wrong, often negative, result | Use double, or rearrange to keep intermediate values small |
| Dividing early to avoid overflow | Run time | A result that is too small (fraction lost) | Prefer double arithmetic when both risks exist |
Will It Overflow?
Without running code, decide which expressions overflow, then check.
1000 * 1000 * 10001000 * 1000 * 1000 * 3Integer.MAX_VALUE - 1 + 1
System.out.println(1000 * 1000 * 1000);
System.out.println(1000 * 1000 * 1000 * 3);
System.out.println(Integer.MAX_VALUE - 1 + 1);
1000000000
-1294967296
2147483647
- 11. One billion is below about 2.1 billion: no overflow.
- 22. Three billion is above the limit: overflow, producing −1,294,967,296.
- 33. Left to right: subtracting 1 first keeps the value in range, then adding 1 returns exactly to the maximum: no overflow.
- 4Estimating helps. Remember the limit as "about 2.1 billion." If a true result could exceed that, an
intis the wrong type.
Changing a * b / c to a / c * b avoids a huge intermediate product, but integer division may now throw away a fraction, giving a different wrong answer. Rearranging is safe only when the division is exact; otherwise use double arithmetic.
A double can hold enormous magnitudes, but it keeps only about 15 to 16 significant digits. For very large whole numbers that must be exact, a double can silently round the last digits. Choose double when range matters more than perfect whole-number precision.
Four Habits for Integer Range
1. Remember "About 2.1 Billion"
Anything that could exceed it does not belong in an int.
2. Watch the Products
Multiplication chains overflow fastest; estimate each step.
3. Distrust Sign Flips
A negative product of positives is overflow until proven otherwise.
4. Use the Constants
Integer.MAX_VALUE and Integer.MIN_VALUE name the limits clearly.
The constant Integer.MAX_VALUE holds the largest possible int value and Integer.MIN_VALUE the smallest. Integer values in Java are represented by values of type int, stored using a finite amount of memory (4 bytes), so an int must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive. If an expression would evaluate to an int outside this range, an integer overflow occurs: the result is an int in the allowed range but not necessarily the value expected.