๐Ÿ“ What Youโ€™ll Learn

  • What type casting is
  • Widening vs narrowing conversion
  • Casting between primitives
  • Casting between objects (reference types)
  • Common pitfalls and tips

๐Ÿ” What is Type Casting?

Type casting is the process of converting a variable from one data type to another.

There are two main types:

  1. Widening (Implicit) โ€“ smaller to larger type (safe)
  2. Narrowing (Explicit) โ€“ larger to smaller type (requires cast)

๐Ÿ”น Widening Casting (Implicit)

Automatically handled by Java. No data loss.

int myInt = 9;
double myDouble = myInt;  // Automatic: int โ†’ double

System.out.println(myDouble);  // 9.0

โœ… Safe and automatic.

๐Ÿ”ธ Narrowing Casting (Explicit)

Must be done manually. Possible data loss.

double myDouble = 9.78;
int myInt = (int) myDouble;  // Manual cast

System.out.println(myInt);  // 9 (decimal part lost)

โš ๏ธ May cause loss of precision or even incorrect results in some cases.

๐Ÿงฎ Casting Between Numeric Types

You can cast between numeric types like int, float, double, etc.

long l = 1000L;
int i = (int) l;  // Needs explicit cast

byte b = (byte) 130;  // Overflow: result is -126

Casting larger to smaller types can cause overflow or truncation.

๐Ÿ”ค Casting Between char and int

char c = 'A';
int ascii = c;  // Implicit: 'A' โ†’ 65

int code = 66;
char letter = (char) code;  // 66 โ†’ 'B'

Useful for working with Unicode and ASCII.

๐Ÿงฑ Casting Reference Types (Objects)

Casting between objects works only when they are in the same inheritance tree.

Animal a = new Dog();   // Upcasting (implicit)
Dog d = (Dog) a;        // Downcasting (explicit)

Always check type before casting with instanceof.

โš ๏ธ Common Pitfalls

  • Overflow/Underflow when narrowing
  • Loss of decimal precision
  • ClassCastException when casting incompatible object types
  • var cannot be used with explicit casts

๐Ÿ“˜ Recap

  • Widening cast: automatic and safe
  • Narrowing cast: must be manual; may lose data
  • Works for both primitive and object types
  • Be cautious with narrowing and reference casts