Exam 1z0-811 All QuestionsBrowse all questions from this exam
Question 9

Given the code fragment:

What is the result?

    Correct Answer: D

    The given code attempts to add elements to specific indices in an ArrayList without populating the list up to those indices first. In Java, the ArrayList's add(int index, E element) method throws an IndexOutOfBoundsException if the specified index is out of range. Initially, the ArrayList is empty, so trying to add an element at index 1 or greater will result in an IndexOutOfBoundsException. Therefore, a runtime exception is thrown.

Discussion
ReachMoOption: D

Index 1 does not exist in the beginning in ArrayList, so index out of bounds

supercoderOption: D

compile and get Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756)

peteVlnOption: D

Yes, this code throws an IndexOutOfBoundsException for begin to add elements at position 1 (and left without data the first element in position at index zero).