๐ 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:
- Widening (Implicit) โ smaller to larger type (safe)
- 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
varcannot 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