Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Integer division and casting

โญ beginnerโณ 14 min read๐Ÿ“ Lesson 6 of 256

final constants, truncated integer division, %, explicit casts.

Java primitives: int (whole numbers), double (decimals), boolean (true/false), char (one character). Anything else on the exam is built from these plus objects.

Constants โ€” the final keyword freezes a variable:

final int MAX_SCORE = 100;
MAX_SCORE = 105;    // compile error โ€” constants never change

Integer division is the trap. When both operands are int, the result is an int โ€” the fractional part is truncated (dropped, not rounded):

System.out.println(7 / 2);     // 3   (not 3.5)
System.out.println(7 % 2);     // 1   (remainder)
System.out.println(7.0 / 2);   // 3.5 (one double operand โ†’ double math)
System.out.println(-7 / 2);    // -3  (truncation toward zero)

Casting converts explicitly:

double d = 9.7;
int truncated = (int) d;          // 9   โ€” decimal part dropped
int rounded = (int) (d + 0.5);    // 10  โ€” the manual rounding trick
double back = truncated;          // widening: no cast needed

Widening (int โ†’ double) is automatic; narrowing (double โ†’ int) needs the cast and loses information.

โšก Now practice

Ready to Code
Typed storageTrace assignments, master integer division, cast safely.
4 challenges ยท ยท ~40 min