Given the code fragment:
1. ArrayList<Integer> list = new ArrayList<>(1);
2. list.add(1001);
3. list.add(1002);
4. System.out.println(list.get(list.size()));
What is the result?
A.
Compilation fails due to an error on line 1.
B.
An exception is thrown at run time due to error on line 3
C.
An exception is thrown at run time due to error on line 4
D.
1002
Explanation:
The code compiles fine.
At runtime an IndexOutOfBoundsException is thrown when the second list item is added.
So B is correct answer
C correct
System.out.println(list.get(list.size()));
list.size() == 2;
list.get(2) => java.lang.IndexOutOfBoundsException
C is correct
ArrayList list = new ArrayList(1); only means that the initial capacity is 1.
So line 3 is no problem.