1.5

Casting and Range of Variables

Casting converts between int and double types, with truncation and overflow risks affecting arithmetic expression results.

1525% of exam
Understand It
Ace It
Context

What this topic is and why it exists

Imagine pouring a gallon of water into a pint glass — something's going to spill.
That's essentially what happens inside your computer when you try to store a number too large for its container.
In Java, an `int` gets exactly four bytes of memory, which means it can only hold values between `Integer.MIN_VALUE` (about negative 2.1 billion) and `Integer.MAX_VALUE` (about positive 2.1 billion).
Go beyond that range, and you get *integer overflow* — Java doesn't crash or warn you; it just wraps around to a completely unexpected number, like an odometer rolling past 999,999 back to zero.
Now here's the other critical move: casting.
When you write `(int) 3.99`, Java doesn't round — it *truncates*, chopping off everything after the decimal point, leaving you with just `3`.
It's like slicing a cake and throwing away the crumbs.
Going the other direction, casting an `int` to a `double`, is gentler — Java simply widens the value, and sometimes this happens automatically when you mix `int` and `double` in the same expression.
The takeaway?
Always know the size of your glass before you pour, and always know what gets lost when you cut between types.
1 / 9