Java OCA OCP Practice Question 3275

Question

What will the program print when compiled and run?.

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

public class Main {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(2007); //from   w w w.  j ava  2s. c om
    list.add(2008); 
    list.add(2009);
    System.out.println("Before: " + list);
    for (int i : list) {
      int index = list.indexOf(i);
      list.set(index, ++i);
    }
    System.out.println("After:  " + list);
  }
}

Select the one correct answer.

(a) Before: [2007, 2008, 2009]// w  w  w.  ja v  a  2s. co  m
    After:  [2008, 2009, 2010]

(b) Before: [2007, 2008, 2009]
    After:  [2010, 2008, 2009]

(c) Before: [2007, 2008, 2009]
    After:  [2007, 2008, 2009]

(d) Before: [2007, 2008, 2009]
    After:  [2008, 2009, 2007]

(e) The program throws a java.util.ConcurrentModificationException when run.


(b)

Note

First note that the indexOf() method returns the index of the first occurrence of its argument in the list.

Although the value of variable i is successively changing during the execution of the loop, it is the first occurrence of this value that is replaced in each iteration:.


After iteration 1: [2008, 2008, 2009]
After iteration 2: [2009, 2008, 2009]
After iteration 3: [2010, 2008, 2009]

Note also that we are not removing or adding elements to the list, only changing the reference values stored in the elements of the list.




PreviousNext

Related