Type Casting (Widening vs Narrowing), Overflow & Underflow
1Concept
Implicit Casting (Widening): Automatic conversion from smaller to larger types (byte -> short -> int -> long -> float -> double) with zero data loss. Explicit Casting (Narrowing): Manual conversion from larger to smaller types (e.g. (int)3.99), causing decimal truncation or bit overflow. Overflow occurs when arithmetic exceeds Integer.MAX_VALUE, wrapping around to Integer.MIN_VALUE.
2Architecture Diagram
Widening (Safe): byte ---> short ---> int ---> long ---> float ---> double Narrowing (Manual): double --(cast)--> float --(cast)--> long --(cast)--> int
3Code Example
Core Java
public class CastingAndOverflow {
public static void main(String[] args) {
int num = 100;
double dbl = num;
System.out.println("Widened int to double: " + dbl);
double price = 99.95;
int truncatedPrice = (int) price;
System.out.println("Narrowed double to int: " + truncatedPrice);
int maxInt = Integer.MAX_VALUE;
int overflowed = maxInt + 1;
System.out.println("Max Int: " + maxInt);
System.out.println("Max Int + 1 (Overflow): " + overflowed);
}
}4Expected Output
Widened int to double: 100.0 Narrowed double to int: 99 Max Int: 2147483647 Max Int + 1 (Overflow): -2147483648
5Key Takeaways
- ✓Explicit narrowing casts discard high-order bits or decimal precision.
- ✓Integer arithmetic wraps around silently upon overflow; use Math.addExact() to throw ArithmeticException.
- ✓Java 10+ var infers types statically at compile time.