OCA Java SE 8 Mock Exam - OCA Mock Question 19








Question

Which of the following are possible outputs of this application? (Choose all that apply)

     0: import java.util.*;
     1: class Shape {} 
     2: interface ShapeFactory { public java.util.List<Shape> getShapes(); } 
     3: public class Main { 
     4:   public static void main(String[] args) { 
     5:     ShapeFactory house = new MyShapeFactory(); 
     6:     Shape chicken = house.getShapes().get(0); 
     7:     for(int i=0; i<house.getShapes().size();
     8:       chicken = house.getShapes().get(i++)) { 
     9:       System.out.println("Shape"); 
     10:    } 
     11: }  
     12:} 
     13:class MyShapeFactory implements ShapeFactory{
     14:      public java.util.List<Shape> getShapes(){
     15:         List<Shape> list = new LinkedList<>();
     16:         list.add(new Shape());
     17:         list.add(new Shape());
     18:         list.add(new Shape());
     19:         list.add(new Shape());
     20:         list.add(new Shape());
     21:         return list;
     22:      }
     23:}
     
  1. The code will not compile because of line 6.
  2. The code will not compile because of lines 7?8.
  3. The application will compile but not produce any output.
  4. The application will output Cluck exactly once.
  5. The application will output Cluck more than once.
  6. The application will compile but produce an exception at runtime.




Answer



E

Note

The code compiles without issue, so options A and B are incorrect.

house.getShapes() returns a list of multiple elements, the code will output Shape once for each element in the array, so option E is correct.

import java.util.LinkedList;
import java.util.List;
/*  w w w  . j  a v a2 s.co m*/
class Shape {
}

interface ShapeFactory {
  public java.util.List<Shape> getShapes();
}

public class Main {
  public static void main(String[] args) {
    ShapeFactory house = new MyShapeFactory();
    Shape chicken = house.getShapes().get(0);
    for (int i = 0; i < house.getShapes().size(); chicken = house
        .getShapes().get(i++)) {
      System.out.println("Checken");
    }
  }
}

class MyShapeFactory implements ShapeFactory {
  public java.util.List<Shape> getShapes() {
    List<Shape> list = new LinkedList<>();
    list.add(new Shape());
    list.add(new Shape());
    list.add(new Shape());
    list.add(new Shape());
    list.add(new Shape());
    return list;
  }
}

The code above generates the following result.