What will happen if an invalid downcast is attempted in Java at runtime?

2025

What will happen if an invalid downcast is attempted in Java at runtime?

  1. A.

    The object will be automatically converted.

  2. B.

    Java will ignore the cast and continue.

  3. C.

    The compiler will throw a syntax error.

  4. D.

    The code will compile but throw ClassCastException at runtime.

Attempted by 50 students.

Show answer & explanation

Correct answer: D

In Java, type casting involves converting an object reference from one type to another. When you attempt a downcast—converting a superclass reference to a subclass reference—the compiler checks if the cast is syntactically valid based on the declared types. If the code compiles successfully, it means the compiler cannot verify at compile-time whether the actual object is of the target subclass type. Consequently, the JVM performs a runtime check to ensure the object's actual class is compatible with the target type. If the object is not an instance of that subclass, the JVM throws a ClassCastException to prevent unsafe type access. Therefore, invalid downcasts do not cause compilation errors but result in a runtime exception.",

Explore the full course: Rssb Senior Computer Instructor