Which exception is thrown on incorrect downcasting?

Get ready for your Object‑Oriented Programming Test. Use flashcards and multiple-choice questions. Each question includes hints and explanations. Prepare for your exam today!

Multiple Choice

Which exception is thrown on incorrect downcasting?

Explanation:
Downcasting from a general type to a more specific type relies on the actual runtime type of the object. If the object isn’t really an instance of the target subclass, the runtime detects the mismatch and throws a ClassCastException. This is the exception that signals an illegal downcast at runtime. Think of downcasting as asking the runtime to treat something as a more specific type than it actually is. If that request isn’t compatible with the real type, you get this exception. The other exceptions don’t describe incorrect downcasting: NullPointerException happens when you use a null reference; ArrayIndexOutOfBoundsException occurs when you access an array with an invalid index; IllegalArgumentException is thrown when a method receives an inappropriate argument. To avoid the issue, you can check the type with instanceof (or equivalent) before casting, or design your code to rely on polymorphism so downcasts aren’t needed.

Downcasting from a general type to a more specific type relies on the actual runtime type of the object. If the object isn’t really an instance of the target subclass, the runtime detects the mismatch and throws a ClassCastException. This is the exception that signals an illegal downcast at runtime.

Think of downcasting as asking the runtime to treat something as a more specific type than it actually is. If that request isn’t compatible with the real type, you get this exception. The other exceptions don’t describe incorrect downcasting: NullPointerException happens when you use a null reference; ArrayIndexOutOfBoundsException occurs when you access an array with an invalid index; IllegalArgumentException is thrown when a method receives an inappropriate argument. To avoid the issue, you can check the type with instanceof (or equivalent) before casting, or design your code to rely on polymorphism so downcasts aren’t needed.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy