ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Object o = "hi";
String s = (String) o;
Integer n = null;
System.out.print((n instanceof Integer) + " " + (o instanceof Comparable) + " ");
Integer bad = (Integer) o;
System.out.print(bad);
  1. A. "true true " is printed, then ClassCastException is thrown
  2. B. Compile-time error at (Integer) o
  3. C. false true hi
  4. D. "false true " is printed, then ClassCastException is thrown

Correct answer: D. "false true " is printed, then ClassCastException is thrown

instanceof is false for null. A String is Comparable. Casting an Object reference to Integer compiles (it might be legal) but fails at run time because the object is a String.

More OOP with C++ and Java questions

Exams that ask this topic