☕ Java
Beginner
What is type casting in Java?
Answer
Type casting is converting a value from one type to another. Widening (implicit) casting converts a smaller type to a larger one automatically without any explicit cast — e.g., int to long, float to double. This is safe and lossless. Narrowing (explicit) casting converts a larger type to a smaller one and requires an explicit cast operator: int x = (int) 9.99; — this can lose data (9.99 becomes 9). For object casting, you can cast a supertype reference to a subtype, but it throws ClassCastException at runtime if the actual object is not of that type. Always check with instanceof before casting.