Casting & Ranges of Values
Converting Between Types (Casting)
Put (int) or (double) right before a value to convert it to that type on the spot:
(double) 1 / 3 // 0.333... — the 1 becomes a double first, then divides
(int) 3.6 // 3 — cuts off everything after the decimal point
(int) always cuts off the decimal — it never rounds. (int) 3.9 is 3, not 4.
If you actually want to round, add 0.5 first, then cast:
int rounded = (int)(5.7 + 0.5); // 6 — this is rounding, not truncating
The Fix for Truncating Division
Lesson 2.2 showed that dividing two whole numbers cuts off the decimal. Casting one of them fixes it — but only if the cast happens before the division:
int total = 17;
int games = 5;
double average = (double) total / games; // correct: 3.4
double wrong = (double) (total / games); // wrong: divides as whole numbers first (3), then casts: 3.0
Whole Numbers Have a Limit
An int can only hold values in a fixed range (roughly ±2.1 billion). Go past that limit, and the number silently wraps around to a wrong value — no error, no warning.
System.out.println(Integer.MAX_VALUE + 1); // wraps to the smallest possible int
This is unlikely to come up in a match, but it's a real risk for a counter that keeps growing and is never reset.
Decimals Have a Precision Limit Too
A double can only store so many digits (about 14-15). Beyond that, the extra digits get quietly rounded off. This is why comparing two decimals with == is risky — two values that "should" be equal might differ by a tiny rounding amount.
Common Pitfalls
- Casting after dividing instead of before. The division already happened as whole numbers by the time the cast runs — putting the cast in the wrong spot doesn't fix anything.
- Assuming a cast rounds.
(int)cuts off the decimal. Rounding needs the add-0.5-then-cast trick.
Key Takeaways
(int)and(double)convert a value's type on the spot;(int)always cuts off decimals, never rounds.- To fix truncating division, cast one of the numbers before dividing — position matters.
intvalues have a fixed range; going past it silently wraps to a wrong value.doublevalues have a precision limit — tiny rounding differences can make==unreliable.
Derived from csawesome-2026: unit-1-using-objects-and-methods/1.05-casting-and-ranges-of-values.md (CSA 1.5)