Java OCA OCP Practice Question 1958

Question

What will be the result of compiling and running the following program?.

import java.util.Iterator;
public class Main<T> implements Iterable<T>{

  private T[] array;
  public Main(T[] array) { this.array = array; }

  public Iterator<T> iterator() {
    return new Iterator<T>() {
      private int next = array.length - 1;

      public boolean hasNext() { return (next >= 0); }
      public T next() {
        T element = array[next];/*from www.j  a v  a  2 s. c o  m*/
        next--;
        return element;
      }
      public void remove() { throw new UnsupportedOperationException(); }
    };
  }
  public static void main(String[] args) {
    String[] array = { "A", "B", "C" };
    Main<String> ra = new Main<String>(array);
    for (String str : ra) {
      System.out.print("|" + str + "|");
    }
  }
}

Select the one correct answer.

  • (a) The program will fail to compile.
  • (b) The program will compile but throw an exception when run.
  • (c) The program will compile and print |A||B||C|, when run.
  • (d) The program will compile and print |C||B||A|, when run.
  • (e) The program will compile and print the strings in an unpredictable order, when run.


(d)

Note

The iterator implemented will traverse the elements of the array in the reverse order, and so will the for(:) loop.

The Iterable and the Iterator interfaces are implemented correctly.




PreviousNext

Related