Java - Type casting Overview-interview
Q1. What is typecasting in Java?
Typecasting in Java is the process of converting one data type into another. It is mainly of two types:
- Widening (Implicit) → smaller type to larger type.
- Narrowing (Explicit) → larger type to smaller type.
Q2. What is the difference between widening and narrowing typecasting?
- Widening (Automatic): Done by Java compiler, no data loss. Example: int → long.
- Narrowing (Manual): Done explicitly by programmer using casting operator, may cause data loss. Example: double → int.
Q3. Why is narrowing typecasting not implicit in Java?
Because narrowing can result in loss of data or precision, Java requires an explicit cast by the programmer to avoid accidental errors.
Q4. Can objects be typecast in Java?
Yes.
- Objects can be cast when there is an inheritance relationship.
- Example: A subclass object can be referenced by a superclass variable (upcasting) and vice versa (downcasting, requires explicit cast).
Q5. What happens if you try to cast incompatible types in Java?
If the types are incompatible (no inheritance or conversion path), Java throws a ClassCastException at runtime.