Given the code fragment:
What is the result?
Given the code fragment:
What is the result?
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.
Index 1 does not exist in the beginning in ArrayList, so index out of bounds
compile and get Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756)
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).