Java OCA OCP Practice Question 2587

Question

Which is a true statement about the following code? (Choose all that apply.)

import java.util. *; 
public class Main { 
   static class Shape { } 
   public static void main(String[] args) { 
      Shape c = new Shape(); 
      ArrayList <Shape> l = new ArrayList<>(); 
      Runnable r = new Thread(); 
      int result = 0; 
      if (c instanceof Shape) result += 1; 
      if (l instanceof Shape) result += 2; 
      if (r instanceof Shape) result += 4; 
      System.out.println(result); 
  } } //w ww.  j a  v  a  2  s  .  c o  m
  • A. The code compiles, and the output is 0.
  • B. The code compiles, and the output is 3.
  • C. The code compiles, and the output is 7.
  • D. c instanceof Shape does not compile.
  • E. l instanceof Shape does not compile.
  • F. r instanceof Shape does not compile.


E.

Note

Code involving instanceof does not compile when there is no way for it to evaluate true.

D not only compiles but it is always true.

E does not compile because ArrayList is a concrete class that does not extend Shape.

F does compile because Runnable is an interface.

In theory, someone could subclass Shape and have the subclass implement Runnable.




PreviousNext

Related