Casting & Range
of Variables
Master how Java converts between primitive types and understand the storage limits that every variable carries.
Java's Primitive Types
Every variable in Java must have a declared type. The AP exam focuses on three primitive types, each storing a different kind and size of data.
Range of int
Range of double
What Is Casting?
Casting is the process of converting a value from one data type to another. Java has two kinds:
Widening Cast: int to double
Narrowing Cast: double to int
Truncation: Toward Zero
When casting from double to int, Java truncates toward zero. This means it chops off the decimal, regardless of whether the value is positive or negative:
Not rounded up to 4
Not rounded down to -4
Even 0.999 becomes 0
Integer Division and Casting
Widening vs. Narrowing
| Widening (Implicit) | Narrowing (Explicit) | |
|---|---|---|
| Direction | int → double | double → int |
| Operator needed? | No | Yes: (int) |
| Data loss? | No (value preserved) | Yes (decimal truncated) |
| Compiler error if omitted? | N/A | Yes |
| Example | double d = 5; | int n = (int) 5.9; |
Integer Overflow
When an arithmetic operation produces a value outside the range of int, the result wraps around silently: no error is thrown.
How to Apply Casting
Example 1: Simple Cast
Example 2: Division Trap
Example 3: Mixed Expressions
Common Mistakes
Summary Table
| Concept | Key Rule | Watch Out |
|---|---|---|
| int range | \(-2^{31}\) to \(2^{31}-1\) | Overflow wraps silently |
| double range | \(\pm 1.8 \times 10^{308}\) | ~15 digits of precision |
| Widening | Automatic (int to double) | No data loss |
| Narrowing | Requires (int) cast | Truncates, does not round |
| Integer division | int / int = int | Cast before dividing |
Question 1 of 5
What is the output of the following code?
System.out.println((int) 7.9);
Question 2 of 5
What value does result hold after this code runs?
double result = 11 / 4;
Question 3 of 5
Which of the following requires an explicit cast to compile?
Question 4 of 5
What is printed by this code?
System.out.println((int) -4.7);
Question 5 of 5
What happens when you add 1 to Integer.MAX_VALUE in Java?