Interview Question

What is ClassCastException?

An incompatible run-time reference cast throws ClassCastException.

💡 Concept ✅ Quick Revision ☕ Java

Answer

ClassCastException is thrown when a reference cast is not valid for the actual object. • The compiler permits casts that are not provably impossible. • The JVM checks narrowing reference casts at run time. • Use instanceof or better type design when a cast is uncertain.

Example

Code
Object value = "Java";
try {
    Integer number = (Integer) value;
} catch (ClassCastException exception) {
    System.out.println("invalid cast");
}
Output
invalid cast

Quick Revision

An incompatible run-time reference cast throws ClassCastException.