AP Computer Science A · Study guide

Integer Range and Overflow

AP® Computer Science A · Using Objects and Methods

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.

Big Picture

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.

Figure 1. Integer values in Java are stored in a finite amount of memory, 4 bytes, so only a fixed set of values can be represented.

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.

Figure 2. An int holds values from Integer.MIN_VALUE to Integer.MAX_VALUE, inclusive. Going past either end wraps around to the other end.
Constant or factValueMeaning
Integer.MAX_VALUE2,147,483,647The largest possible int value
Integer.MIN_VALUE−2,147,483,648The smallest possible int value
Storage for an int4 bytes (32 bits)A finite amount of memory, so a finite range
Integer.MAX_VALUE + 1−2,147,483,648Overflow wraps to the minimum
Integer.MIN_VALUE - 12,147,483,647Overflow wraps to the maximum
Worked Example 1 The limits

Printing the Range and Stepping Past It

Predict the output.

Code
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);
Output
2147483647
-2147483648
-2147483648
2147483647
  1. 1The constants. Integer.MAX_VALUE is 2,147,483,647 and Integer.MIN_VALUE is −2,147,483,648.
  2. 2One past the maximum. Adding 1 to the largest int overflows and wraps around to the smallest.
  3. 3One below the minimum. Subtracting 1 from the smallest int wraps around to the largest.
  4. 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.
Result: The program prints the two limits and then shows each one wrapping to the other. Integer overflow produces a valid 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.

Figure 3. Overflow works like a mechanical odometer: with a fixed amount of storage, counting past the largest value starts over. For an int, it restarts at the most negative value.
Worked Example 2 Multiplication

When Squaring Overflows

The square root of Integer.MAX_VALUE is about 46,340.95. Predict both results.

Code
int a = 46340;
int b = 46341;
System.out.println(a * a);
System.out.println(b * b);
Output
2147395600
-2147479015
  1. 146,340². 2,147,395,600 fits below the limit, so it is correct.
  2. 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.
  3. 3A warning sign. A negative result from multiplying two positive numbers is a classic symptom of overflow.
Result: The first square is correct; the second overflows to a negative number. Multiplying values in the tens of thousands can already exceed the range of int.
Common Mistake 1 · Expecting an Error Message

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.

Figure 4. The true square of 46,341 is only slightly larger than the largest int, but the overflowed result is wildly wrong and even negative.
QuantityRough sizeFits in an int?
Students in a schoolThousandsYes
Seconds in a yearAbout 31.5 millionYes
Milliseconds in a monthAbout 2.6 billionNo
People on EarthAbout 8 billionNo
A large city's populationMillionsYes
Worked Example 3 Real quantities

How Many Seconds in 70 Years?

A program computes the number of seconds in 70 years (ignoring leap days). Predict both results.

Code
int seconds = 70 * 365 * 24 * 60 * 60;
System.out.println(seconds);
double secondsD = 70 * 365 * 24 * 60 * 60.0;
System.out.println(secondsD);
Output
-2087447296
2.20752E9
  1. 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.
  2. 2The double version. Multiplying by 60.0 makes the last step a double operation. The earlier steps, ending at 36,792,000, fit comfortably in an int, so nothing overflows.
  3. 3Scientific notation. Large double values print in E notation: 2.20752E9 means 2.20752 × 10⁹ = 2,207,520,000.
Result: The 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.
Worked Example 4 Order of operations

Rearranging to Stay in Range

A program computes 60,000 × 60,000 ÷ 40,000 two ways. Predict both.

Code
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));
Output
-17374
60000
60000
  1. 1Line 1. x * y is 3,600,000,000, which overflows before the division ever happens, giving garbage.
  2. 2Line 2. x / z is 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.
  3. 3Line 3. Same problem: y / z is 1, so the result is 60,000.
  4. 4A correct approach. Use double arithmetic, such as (double) x * y / z, which gives 90000.0.
Result: Multiplying first overflowed; dividing first truncated. Neither int ordering is correct here, which is a signal to switch to double arithmetic.
Common Mistake 2 · Checking Only the Final Answer's Size

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.

Worked Example 5 Compile-time limits

A Literal That Is Too Large

Explain the compiler error.

Code that does not compile
int population = 8100000000;
  1. 1The literal itself is invalid. 8,100,000,000 is outside the int range, so the compiler rejects the number before the program can run.
  2. 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 int at all.
  3. 3A workable choice. A value this large can be stored as a double (8.1E9 or 8100000000.0), as long as exact whole-number precision is not essential.
Result: The compiler reports "integer number too large." A literal outside the 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.

ProblemWhen it appearsSymptomFix
Literal too largeCompile time"integer number too large"Use a double literal or rethink the units
Overflow in a calculationRun time (silent)A wrong, often negative, resultUse double, or rearrange to keep intermediate values small
Dividing early to avoid overflowRun timeA result that is too small (fraction lost)Prefer double arithmetic when both risks exist
Worked Example 6 Reasoning

Will It Overflow?

Without running code, decide which expressions overflow, then check.

  1. 1000 * 1000 * 1000
  2. 1000 * 1000 * 1000 * 3
  3. Integer.MAX_VALUE - 1 + 1
Code
System.out.println(1000 * 1000 * 1000);
System.out.println(1000 * 1000 * 1000 * 3);
System.out.println(Integer.MAX_VALUE - 1 + 1);
Output
1000000000
-1294967296
2147483647
  1. 11. One billion is below about 2.1 billion: no overflow.
  2. 22. Three billion is above the limit: overflow, producing −1,294,967,296.
  3. 33. Left to right: subtracting 1 first keeps the value in range, then adding 1 returns exactly to the maximum: no overflow.
  4. 4Estimating helps. Remember the limit as "about 2.1 billion." If a true result could exceed that, an int is the wrong type.
Result: Only the second expression overflows. A quick size estimate against 2.1 billion catches most overflow risks before any code runs.
Common Mistake 3 · Fixing Overflow by Dividing First

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.

Common Mistake 4 · Assuming double Fixes Everything for Free

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.

Core Synthesis

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.