OCA Java SE 8 Core Java APIs - OCA Mock Question Core Java APIs 2-5








Question

Which of the following are true statements about the following code?

public class Main{
   public static void main(String[] argv){
         List<Integer> myArrayList = new ArrayList<>(); 
         myArrayList.add(Integer.parseInt("5")); 
         myArrayList.add(Integer.valueOf("6")); 
         myArrayList.add(7); 
         myArrayList.add(null); 
         for (int age : myArrayList) 
            System.out.print(age); 
   }
}
  1. The code compiles.
  2. The code throws a runtime exception.
  3. Exactly one of the add statements uses autoboxing.
  4. Exactly two of the add statements use autoboxing.
  5. Exactly three of the add statements use autoboxing.




Answer



A, B, D.

Note

The following two lines use autoboxing to convert an int to an Integer.

     myArrayList.add(Integer.parseInt("5")); 
     myArrayList.add(7); 

valueOf() returns an Integer so the following line is not using autoboxing.

myArrayList.add(Integer.valueOf("6")); 

myArrayList.add(null); does not do the autoboxing because null is not an int.

The code does compile.

When the for loop tries to unbox null into an int, it fails and throws a NullPointerException.