Mastering Java: The Ultimate Quiz for 'Thinking in Java'

Disable ads (and more) with a membership for a one time $2.99 payment

Mastering Java: The Ultimate Quiz for 'Thinking in Java'. Dive deep into Java with multiple-choice questions. Challenge yourself with quiz questions designed to test and improve your understanding of the 'Thinking in Java' book. Get ready for your exam!

Practice this question and more.


What exception is thrown if a downcast fails in Java?

  1. NullPointerException

  2. ClassCastException

  3. RuntimeException

  4. IllegalArgumentException

The correct answer is: ClassCastException

A downcast in Java is when an object is converted from a superclass type to a subclass type. The ClassCastException is thrown when an attempt to perform this conversion fails, indicating that the object is not an instance of the specified subclass. This is different from a NullPointerException, which is thrown when a null object is accessed, and from a RuntimeException, which is a general exception that is not specifically related to downcasting. Similarly, an IllegalArgumentException is thrown when an invalid argument is passed to a method, so it is not directly related to downcasting. Thus, the ClassCastException is the most appropriate exception to be thrown when a downcast fails in Java.