Widening and Narrowing Conversions
Learn automatic widening conversions and how to perform explicit narrowing casts safely.
Type Conversions in Java
Java allows converting values between compatible types. There are two directions:
- Widening — converting to a larger type (safe, automatic)
- Narrowing — converting to a smaller type (risky, requires explicit cast)
Widening Conversion
Widening happens automatically when you assign a value to a larger compatible type. No data is lost because the target type can represent all values of the source.
Widening order: byte → short → int → long → float → double
byte b = 42;
short s = b; // byte → short (widening)
int i = s; // short → int (widening)
long l = i; // int → long (widening)
float f = l; // long → float (widening)
double d = f; // float → double (widening)
System.out.println(d); // 42.0All lessons in this course
- Primitive vs Reference Types
- Widening and Narrowing Conversions
- The instanceof Operator
- Type Casting in Practice