Java OCA OCP Practice Question 818

Question

What will the following code print when compiled and run?

import java.util.*; 
public class Main  { 
    public static void main (String [] args) throws Exception  { 
        ArrayList<String> al = new ArrayList<String> (); 
        al.add ("111"); 
        al.add ("222"); 
        System .out.println (al.get (al.size ())); 
      } 
} 

Select 1 option

  • A. It will not compile.
  • B. It will throw a NullPointerException at run time.
  • C. It will throw an IndexOutOfBoundsException at run time.
  • D. 222
  • E. null


Correct Option is  : C

Note

For Option C.

size() method of ArrayList returns the number of elements.

It returns 2.

Since numbering in ArrayList starts with 0.

al.get(2) will cause an IndexOutOfBoundsException to be thrown because only 0 and 1 are valid indexes for a list of size 2.




PreviousNext

Related