Java OCA OCP Practice Question 2638

Question

Consider the following program:

import java.util.ArrayList;

class Main {/*from   ww  w . j  a  v  a2s  . c o  m*/
       static ArrayList<Integer> doSomething(ArrayList<Integer> values) {
               values.add(new Integer(10));
               ArrayList<Integer> tempList = new ArrayList<Integer>(values);
               tempList.add(new Integer(15));
               return tempList;
       }
       public static void main(String []args) {
               ArrayList<Integer> allValues = doSomething(new ArrayList<Integer>());
               System.out.println(allValues);
       }
}

This program prints the following:

  • a) []
  • b) [10]
  • c) [15]
  • d) [10, 15]


d)

Note

In this program, the reference allValues is passed to the doSomething() method.

In this container, the element with value 10 is added.

Following that, a new container is created by copying the elements of the current reference, so the value 10 is copied to the new container as well.

Since element 15 is added in addition to the existing element 10, and the reference to the container is returned; the program prints [10, 15].




PreviousNext

Related