ProgrammingHardProduct-company interview pattern

What happens when this Java code is compiled and run?

What happens when this Java code is compiled and run?
Object o = new ArrayList<String>();
List<String> l = (List<String>) o;
String s = (String) o;
System.out.print("done");
  1. A. Compilation error at the third line
  2. B. It compiles; a ClassCastException is thrown at the third line
  3. C. It prints done
  4. D. ClassCastException at the second line

Correct answer: B. It compiles; a ClassCastException is thrown at the third line

Casting from Object to String is a legal downcast, so it compiles; at run time the object is an ArrayList, not a String, so the cast throws ClassCastException. The cast to List<String> succeeds (it only gives an unchecked warning).

More OOP with C++ and Java questions

Exams that ask this topic