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 type of error will you get if you add an Orange to an ArrayList of Apples and then try to cast it to an Apple?

  1. Compile-time error

  2. Logical error

  3. Runtime exception

  4. Syntax error

The correct answer is: Runtime exception

Trying to cast an Orange to an Apple will result in a Runtime exception. This is because Java enforces type safety and does not allow incompatible types to be casted. Since Orange and Apple are not subclasses of each other, it will throw a ClassCastException at runtime. A Compile-time error is not applicable here because there is no syntax error, and the code will compile without any issues. A logical error is also not applicable because the code will not produce an incorrect output, but rather fail to execute at runtime. A Syntax error is also not applicable because there is no error in the syntax of the code.