Given the following code fragment:
Which inserted code will print DCBA?
DCBA
The list holds four elements at indexes 0 through 3. Initializing the index to the list size (4) and looping while it is at least 1, each iteration pre-decrements the index before calling get, so the elements at indexes 3, 2, 1, and 0 are printed in that order, producing DCBA. Starting from size minus 1 but looping only while the index is at least 1 stops before index 0 and prints only DCB; resetting the index to the list size inside the loop reprints the last element forever; and post-decrementing from the list size accesses index 4 first, which throws an IndexOutOfBoundsException.
get
DCB
IndexOutOfBoundsException
Community Discussion