Java OCA OCP Practice Question 1383

Question

What is the output of the following?

List<String> l = Arrays.asList("can", "cup"); 
for (int container = l.size(); container > 0; container++) { 
   System.out.print(l.get(container-1) + ","); 
} 
  • A. can,cup,
  • B. cup,can,
  • C. The code does not compile.
  • D. This is an infinite loop.
  • E. The code compiles but throws an exception at runtime.


E.

Note

In the first iteration through the loop, container is 2 and cup is printed.

The loop body subtracts 1 to account for indexes being zero based in Java.

Then the update statement runs, setting container to 3.

The condition is run and sees that 3 is in fact greater than 0.

The loop body subtracts 1 and tries to get the element at index 2.

There isn't one and the code throws an exception.

This makes Option E correct.




PreviousNext

Related