Topic 1.5 — Casting and Range of Variables

Goal: understand how Java converts between numeric types (especially int and double), use casting when needed, and recognize that primitive numeric types have limited ranges.

The big idea

Java stores numbers using a fixed amount of memory. That means each numeric type has a range, and converting between types can change the value (especially when decimals are involved).

Casting is how you tell Java: “treat this value as a different type.”

Two conversions you’ll see the most

  • intdouble: safe widening conversion (keeps the value).
  • doubleint: narrowing conversion (drops the decimal part).

AP note: converting double to int truncates toward zero.

Widening conversion (automatic)

When Java can convert without losing information, it will do it automatically.

int x = 7;
double y = x;   // y becomes 7.0

This is common in expressions like 7 / 2.0.

Narrowing conversion (cast required)

Java requires a cast when information might be lost (like decimals).

double d = 8.9;
int n = (int) d;   // n becomes 8

The fractional part is removed (not rounded).

Truncation examples (toward zero)

(int) 3.99   // 3
(int) 3.01   // 3
(int) -2.7   // -2

“Toward zero” means negative values move up toward 0 (e.g., -2.7 becomes -2).

Casting inside expressions

A cast affects the value right where it appears.

double avg = (double) (7 + 8) / 2;  // 7.5

Without the cast, (7 + 8) / 2 would be integer division first.

Common mistake: expecting rounding

Casting does not round. It truncates.

(int) 9.9   // 9, not 10

Range of variables (why it matters)

A type can only store values within a certain range. If a value goes beyond that range, you get incorrect results (overflow).

For Unit 1, you mostly need the idea: ints have limits.

Overflow idea (conceptual)

If an int is pushed past its maximum, it “wraps around” to a negative value.

// Conceptual example (exact max value not required here)
int big = 2147483647;   // max int
big = big + 1;          // overflow → becomes negative

Exam mindset

  • If Java can widen safely (int → double), it happens automatically.
  • If narrowing (double → int), you must cast.
  • Casting double to int truncates (doesn’t round).
  • Remember that numeric types have limits (overflow can happen).

Quick self-check

  1. What is the value of (int) 5.99?
  2. What is the value of (int) -3.2?
  3. Why does double d = 7; work without a cast?
  4. Why does int n = 7.2; not compile?
  5. Why might overflow cause “weird” results?

← Back to Unit 1 topics