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?

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 2

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


Aaron

Aaron

I think the correct answer is : A.

Because ArrayList list = new ArrayList(1);

missing “Integer” between “”

ArrayList list= new ArrayList(1);

without Integer there is a compilation error.

Anca

Anca

The correct answer is C, because list.size()=2 and ArrayList has 2 positions: 0 and 1.
You can’t execute list.get(2)because doesn’t exist that position.