What is the result?

Given the code fragment:
<code>
1. ArrayList<Integer> list = new ArrayList<>(1);
2. list.add(1001);
3. list.add(1002);
4. System.out.println(list.get(list.size()));
</code>
What is the result?

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.



Leave a Reply 3

Your email address will not be published. Required fields are marked *


sully

sully

So B is correct answer

Rolandas

Rolandas

C correct

System.out.println(list.get(list.size()));

list.size() == 2;
list.get(2) => java.lang.IndexOutOfBoundsException

Oene Bakker

Oene Bakker

C is correct

ArrayList list = new ArrayList(1); only means that the initial capacity is 1.
So line 3 is no problem.