Cast Operators
1. What Casting Means (beginner)
Cast = convert one type to another with (type) prefix. Needed because Java is strict: int won't silently become byte, double won't fit int without your permission.
2. Widening (safe, auto) vs Narrowing (risky, manual)
int i = 100;
long l = i; // widening int→long: AUTO, safe (small→big)
double d = 7; // int→double auto → 7.0
double pi = 3.99;
int x = (int) pi; // narrowing: MANUAL cast, cuts → 3 (decimal LOST!)
byte b = (byte) 258; // 258 % 256 = 2! (overflow wraps — trap!)
char c = (char) 65; // 65 → 'A'
| Direction | Example | Needs cast? | Data loss? |
|---|---|---|---|
| byte→int→long→float→double | int→double |
No (auto) | No |
| double→int, int→byte | (int)3.99 |
Yes (type) |
Yes (cut/overflow) |
3. Beginner Average Fix (classic!)
int total = 7, n = 2;
System.out.println(total / n); // 3 (int/int trap)
System.out.println((double) total / n); // 3.5 (cast one side → double math!)
4. Object Casting Preview (Module 3)
(Child) parentObj downcast needs check: if (obj instanceof Child) first, else ClassCastException.
5. Exam Points
- Widening vs narrowing +
(double)total/nfix — 5-7 marks, very frequent. (byte)258overflow +(int)3.99truncation — 3-5 marks, favourite traps.