All topics
library
beginner

Type Casting: Widening & Narrowing

Know when Java casts automatically (widening), when you must cast explicitly (narrowing), and the data loss risks.

Java has two types of type conversion:

Widening = pouring a small glass of water into a big glass (always fits). Narrowing = pouring a big glass into a small one (overflow/loss).

Key Concepts

1
Widening (implicit): converting a smaller type to a larger type. No data loss. byte → short → int → long → float → double. Also char → int. The compiler inserts the conversion automatically.
2
Narrowing (explicit): converting a larger type to a smaller type. Requires an explicit cast and may lose data. double → float → long → int → short → byte. The compiler rejects this without an explicit cast.
3
Subtle data loss cases: - int to float: int has 32 bits of precision for integers; float has only 24 bits for the significand. Large ints lose precision when widened to float (this is a widening conversion that loses data!). - long to float/double: similar precision loss. - Narrowing truncates: (byte) 256 → 0 (wraps around). (int) 3.99 → 3 (truncates, doesn't round).
4
Reference type casting: upcasting (Dog → Animal) is always safe and implicit. Downcasting (Animal → Dog) requires an explicit cast and can throw ClassCastException at runtime. Use instanceof before downcasting.
5
Since Java 16, pattern matching for instanceof eliminates the need for a separate cast: if (obj instanceof String s) { use s directly }.