AP® Computer Science A · Unit 1 · Topic 1.5

The Range of an int and Overflow

An int is stored in exactly 32 bits, so it can only hold values from -2,147,483,648 to 2,147,483,647. Push past that top edge and the value silently wraps around to the most negative int instead of growing.

An int in Java is always 32 bits, no more, no less. Thirty-two bits can represent exactly 232 different patterns, and Java splits that range so roughly half the patterns represent negative numbers and half represent nonnegative ones. That gives a ceiling, Integer.MAX_VALUE, which is 2,147,483,647, and a floor, Integer.MIN_VALUE, which is -2,147,483,648. There is no bit pattern left over for 2,147,483,648. The int does not expand to make room, because its size is fixed at compile time.

So what happens when you add 1 to the biggest int? The bits just do normal binary addition, and the carry that would need a 33rd bit falls off the end and is thrown away. The leftover pattern is read back using the same rule that made MAX_VALUE positive and MIN_VALUE negative, and that pattern happens to mean -2,147,483,648. Java does not throw an error or warn you. The program keeps running with a wildly wrong value, which is exactly why overflow bugs are dangerous: nothing looks broken until the numbers do.

This matters right after you meet variables and expressions, because it is the first place a seemingly correct line of code gives a wrong answer for a reason that has nothing to do with logic and everything to do with storage. The fix, when a value might exceed about 2 billion, is to switch to a type with more room, like double or long, trading away the fixed 32-bit ceiling for a much wider range, at the cost of some precision for double.

Key terms

Overflow
When a calculation produces a value too large or small for its type's fixed number of bits, causing it to wrap around.
Integer.MAX_VALUE
The largest value an int can hold, 2,147,483,647.
Integer.MIN_VALUE
The smallest value an int can hold, -2,147,483,648.
32-bit
The fixed storage size of an int in Java, giving it exactly 232 possible values.
double
A 64-bit floating-point type with a much wider range than int, used when values might exceed int's limits.

Watch it explained

  1. How it worksHow do 32 bits set a hard ceiling and a hard floor on the values an int can hold?
  2. How it worksWalk me through what happens to the bits when you add 1 to Integer.MAX_VALUE.
  3. Worked exampleFind what Integer.MAX_VALUE + 1 prints and where that value lands on the number line.
  4. Going furtherWhat changes about the range when you store the same huge count in a double instead?

Check yourself

Your turn1 of 2
int x = Integer.MAX_VALUE; x = x + 1; System.out.println(x); What does this print?

End of topic.