Java - Interview Questions and Answers on Casting

Q1.  What is casting?

Ans. Casting is the process of converting literal and references from one type to other.

There are two types of casting - casting between primitive types and casting between object references. 

Q2.  Difference between implicit and explicit type casting ?

Ans. An explicit conversion is where you use some syntax to tell the program to do a conversion whereas in case of implicit type casting you need not provide the target data type explicitly. 

Q3.  When do you get ClassCastException?

Ans. As we downcast objects, The ClassCastException is thrown in case code has attempted to cast an object to a subclass of which it is not an instance.

Q4.  What is Generalization and Specialization in terms of casting ?

Ans. Generalization or UpCasting is a phenomenon where a sub class is prompted to a super class, and hence becomes more general. Generalization needs widening or up-casting. Specialization or DownCasting is a phenomenon where a super class is narrowed down to a sub class. Specialization needs narrowing or down-casting.