Java OCA OCP Practice Question 2411

Question

Which of the following statements are correct?

a  The following code executes without an error or exception: 

       ArrayList<Long> lst = new ArrayList<>(); 
       lst.add(10); //w w  w.  java 2 s .  c o  m

b  Because ArrayList stores only objects, you can't pass an element of an 
   ArrayList to a switch construct. 
   
c  Calling clear () or remove() on an ArrayList will remove all its elements. 

d  If you frequently add elements to an ArrayList, specifying a larger capacity will 
   improve the code efficiency. 

e  Calling the method clone() on an ArrayList creates its shallow copy; that is, it 
       doesn't clone the individual list elements. 


d, e

Note

Option (a) is incorrect.

The default type of a non-floating numeric literal value is int.

You can't add an int to an ArrayList of type Long.

You can pass values of type Long or long to its add method.

Option (b) is incorrect.

Starting with Java 7, switch also accepts variables of type String.

Because a String can be stored in an ArrayList, you can use elements of an ArrayList in a switch construct.

Option (c) is incorrect.

Only clear () will remove all elements of an ArrayList.

Option (d) is correct.

An ArrayList internally uses an array to store all its elements.

Whenever you add an element to an ArrayList, it checks whether the array can accommodate the new value.

If it can't, ArrayList creates a larger array, copies all the existing values to the new array, and then adds the new value at the end of the array.

If you frequently add elements to an ArrayList, it makes sense to create an ArrayList with a bigger capacity because the previous process isn't repeated for each ArrayList insertion.

Option (e) is correct.

Calling clone() on an ArrayList will create a separate reference variable that stores the same number of elements as the ArrayList to be cloned.

But each individual ArrayList element will refer to the same object; that is, the individual ArrayList elements aren't cloned.




PreviousNext

Related