Limitations of Data Types
Understanding Variable Ranges
Every variable in Java has a data type, and every data type can store only a limited range of values. If you try to store a value that is outside of that range, the result depends on the type of variable and how the value is assigned.
Understanding variable ranges helps you choose the right data type and avoid unexpected results in your programs.
Variable Ranges
Each primitive numeric type has a minimum and maximum value.
| Data Type | Minimum Value | Maximum Value |
|---|---|---|
byte |
-128 | 127 |
short |
-32,768 | 32,767 |
int |
-2,147,483,648 | 2,147,483,647 |
long |
-9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
If you need to store a value outside the range of one data type, choose a larger data type.
Assigning a Value Outside the Range
The Java compiler checks whether a value fits in the variable's type.
For example, the following code does not compile because 200 is outside the range of a byte.
The compiler reports an error because the value cannot be represented by a byte.
Changing the variable to an int solves the problem.
Try it in the Java Playground
- Attempt to run the code.
- Update the data type to be
int
Integer Overflow
Even if the original values are within range, the result of an arithmetic operation might not be.
The mathematical result is larger than the maximum value an int can store.
When this happens, an integer overflow occurs.
When an integer value exceeds the largest value that can be stored, it wraps around to the other end of the range.
Instead of producing a larger positive number, the value wraps to the smallest possible int.
Similarly, subtracting 1 from the smallest int wraps around to the largest int.
Overflow does not cause an exception. Instead, the stored value becomes incorrect because it has wrapped around.
Try it in the Java Playground
- Attempt to run the code.
- Add one to
valuewithvalue++;. Print value to the console. - Change
MAX_VALUEtoMIN_VALUEandvalue++tovalue--
Why Does Range Matter?
Choosing a data type that is too small can produce incorrect results.
For example:
- A counter may suddenly become negative.
- A calculation may produce an unexpected value.
- A program may behave incorrectly because an overflow occurred.
Selecting a data type with an appropriate range helps prevent these problems.