Java OCA OCP Practice Question 3014

Question

Given:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
   public static void main(String[] args) {
      List g = new ArrayList();
      g.add(new Shape("Java"));
      g.add(new Shape("SQL"));
      g.add(new Shape("Javascript"));
      Iterator i2 = g.iterator();
      while (i2.hasNext()) {
         System.out.print(i2.next().name + " ");
      }/*ww  w . j  av a2s .  co  m*/
   }
}

class Shape {
   public String name;

   Shape(String n) {
      name = n;
   }
}

What is the result?

  • A. SQL Javascript
  • B. Javascript Java SQL
  • C. Javascript SQL Java
  • D. Java SQL Javascript
  • E. Compilation fails.
  • F. The output order is unpredictable.


E is correct.

Note

Iterator's next() method returns an Object, which in this case needs to be cast to a Shape before its name property can be used.




PreviousNext

Related