OCA Java SE 8 Mock Exam - OCA Mock Question 6








Question

What is the result of the following code?

public class Main{
  public static void main(String[] argv){
     int[] array = {6,9,8}; 
     List<Integer> list = new ArrayList<>(); 
     list.add(array[0]); 
     list.add(array[2]); 
     list.set(1, array[1]); 
     list.remove(0); 
     System.out.println(list); 
  }
}
  1. [8]
  2. [9]
  3. Something like [Ljava.lang.String;@1a3df1c1
  4. An exception is thrown.
  5. The code does not compile.




Answer



B.

Note

The following code creates an array to use an anonymous initializer because it is in the same line as the declaration.

int[] array = {6,9,8}; 

The ArrayList is using the diamond operator introduced since Java 7.

List<Integer> list = new ArrayList<>(); 

The diamond operator specifies the type from right matches the one on the left without having to re-type it.

After adding the two elements, list contains [6, 8].

The code then replaces the element at index 1 with 9, resulting in [6, 9].

Finally, we remove the element at index 0, leaving [9].

import java.util.ArrayList;
import java.util.List;
/*from  www. j  a v  a  2s .c om*/
public class Main{
  public static void main(String[] argv){
     int[] array = {6,9,8}; 
     List<Integer> list = new ArrayList<>(); 
     System.out.println("list:"+list); 
     list.add(array[0]); 
     System.out.println("list:"+list); 
     list.add(array[2]); 
     System.out.println("list:"+list); 
     list.set(1, array[1]); 
     System.out.println("list:"+list); 
     list.remove(0); 
     System.out.println("list:"+list); 
     System.out.println(list); 
  }
}

The code above generates the following result.