Java OCA OCP Practice Question 2402

Question

Which code option(s) when inserted at //INSERT CODE HERE will make class Main print A?.

class Main {
    public static void main(String args[]) {
            String myArray[] = {"A", "B", "C", "D"};
            //INSERT CODE HERE
           System.out.println(myArrayList.get(0));
    }
}
a  List <?> myArrayList = new LinkedList<?>(Arrays.asList(myArray));
b  List <?> myArrayList = new LinkedList<>(Arrays.asList(myArray));
c  List <? extends String> myArrayList = new LinkedList<>(Arrays.asList(myArray));
d  List myArrayList = new LinkedList(Arrays.asList(myArray));
e  List myArrayList = new LinkedList<String>(Arrays.asList(myArray));


b, c, d, e

Note

Option (a) is incorrect.

This code won't compile.

When Java runtime instantiates a LinkedList object, it must know the type of objects that it stores-either implicitly or explicitly.

But, in this option, the type of the LinkedList object is neither stated explicitly nor can it be inferred.

Option (b) is correct.

The wildcard ? is used to refer to any type of object.

Here you're creating a reference variable myArrayList, which is a List of any type.

This reference variable is initialized with LinkedList object, whose type is inferred by the argument passed to the constructor of LinkedList.

Option (c) is correct.

This option uses the bounded wildcard <? extends String>, restricting the unknown type to be either class String or any of its subclasses.

Even though String is a final class, ? extends String is acceptable code.

Option (d) generates a compiler warning because it uses raw types.

Option (e) doesn't generate a compiler warning because the object creation uses generics.




PreviousNext

Related