Memra

Casting & numeric promotion

How Java widens, narrows, and promotes numbers — a top exam trap.

Mixing numeric types

Widening (small → big) is automatic and safe: intlongdouble. Narrowing (big → small) can lose data, so it needs an explicit cast:

double d = 9.99;
int i = (int) d;   // 9 — the fraction is truncated, not rounded

Binary numeric promotion is the rule that surprises people: in an arithmetic expression, byte, short, and char are promoted to int before the operation. So byte a = 1, b = 2; then a + b is an int, and byte c = a + b; won't compile without a cast.

The one exception is compound assignment (+=, *=, …), which has a *hidden* cast back to the variable's type: a += b; compiles and silently narrows the result back to byte.

NORMAL ~/memra/learn/java-from-zero/casting-and-promotion utf-8 LF