← Back to Week 1 Hub

Widening vs Narrowing

Type Conversions in Java — The Cup Analogy • Workbook 1c, p.62-63

The Widening Path (safe, automatic)

byte1 byte
safe
short2 bytes
safe
int4 bytes
safe
long8 bytes
safe
float4 bytes
safe
double8 bytes
char2 bytes
safe
int4 bytes

Widening — SAFE (Small → Big)

int
4 bytes
double
8 bytes
int x = 42;
double y = x; // automatic, safe!
✔ Widening — Java does this automatically

Narrowing — DANGEROUS (Big → Small)

double
8 bytes
int
4 bytes
double price = 19.99;
int rounded = (int) price; // must cast! Loses .99!
⚠ Narrowing — Requires explicit cast, may lose data
Lost: .99 — result is 19, not 19.99!

Try It — Pick a Conversion

Select types above and click Try It!

Quick Examples (click to explore)

byte b = 42;
int i = b;
✔ Safe! Widening (byte → int)
int i = 1000;
byte b = (byte) i;
⚠ Overflow! 1000 → byte = -24
double d = 9.7;
int i = (int) d;
⚠ Truncated! 9.7 → 9 (chopped, not rounded)

Key Takeaway

Widening = small → big = automatic = safe
Java handles it for you. No data is lost.
double y = myInt;
Narrowing = big → small = needs (cast) = may lose data
You must explicitly tell Java. Data may be lost!
int x = (int) myDouble;
← Pre/Post Increment printf Format Specifiers →