Java OCA OCP Practice Question 2413

Question

What is the output of the following code?

import java.util.*;                                    // line 1 
public class Main {                                    // line 2 
    public static void main(String args[]) {           // line 3 
        ArrayList<String> l = new ArrayList<>();       // line 4 
        l.add("One");                                  // line 5 
        l.add("Two");                                  // line 6 
        System.out.println(l.contains(new String("One")));// line 7 
        System.out.println(l.indexOf("Two"));          // line 8 
        l.clear ();                                    // line 9 
        System.out.println(l);                         // line 10 

        System.out.println(l.get(1));                  // line 11 
    }                                                  // line 12 
}                                                      // line 13 
  • a Line 7 prints true.
  • b Line 7 prints false.
  • c Line 8 prints -1.
  • d Line 8 prints 1.
  • e Line 9 removes all elements of the list l.
  • f Line 9 sets the list l to null.
  • g Line 10 prints null.
  • h Line 10 prints [].
  • i Line 10 prints a value similar to ArrayList@16356.
  • j Line 11 throws an exception.
  • k Line 11 prints null.


a, d, e, h, j

Note

Line 7: The method contains accepts an object and compares it with the values stored in the list.

It returns true if the method finds a match and false otherwise.

This method uses the equals method defined by the object stored in the list.

In the example, the ArrayList stores objects of class String, which has overridden the equals method.

The equals method of the String class compares the values stored by it.

This is why line 7 returns the value true.

Line 8: indexOf returns the index position of an element if a match is found; otherwise, it returns -1.

This method also uses the equals method behind the scenes to compare the values in an ArrayList.

Because the equals method in the class String compares its values and not the reference variables, the indexOf method finds a match in position 1.

Line 9: The clear method removes all the individual elements of an ArrayList such that an attempt to access any of the earlier ArrayList elements will throw a runtime exception.

It doesn't set the ArrayList reference variable to null.

Line 10: ArrayList has overridden the toString method such that it returns a list of all its elements enclosed within square brackets.

To print each element, the toString method is called to retrieve its String representation.

Line 11: The clear method removes all the elements of an ArrayList.

An attempt to access the (nonexistent) ArrayList element throws a runtime IndexOutOfBoundsException exception.

This question tests your understanding of ArrayList and determining the equality of String objects.




PreviousNext

Related