ProgrammingVery hardProduct-company placement · Java

Which lines fail to compile?

Which lines fail to compile?
String s = "x"; Number n = 1; Runnable r = () -> { }; Object o = s;
boolean a = s instanceof Integer;    // L1
boolean b = n instanceof Integer;    // L2
boolean c = r instanceof String;     // L3
boolean d = o instanceof Runnable;   // L4
  1. A. L1 only
  2. B. L1, L3 and L4
  3. C. L1 and L3
  4. D. L3 only

Correct answer: C. L1 and L3

instanceof is a compile-time error when the cast could never succeed. String and Integer are unrelated classes (L1); String is final and does not implement Runnable, so no Runnable can be a String (L3). Number and Object can hold the tested types.

More OOP with C++ and Java questions

Exams that ask this topic