Given: 11. public static Iterator reverse(List list) { 12. Collections.reverse(list); 13. return list.iterator(); 14. } 15. public static void main(String[] args) { 16. List list = new ArrayList(); 17. list.add(” 1”); list.add(”2”); list.add(”3”); 18. for (Object obj: reverse(list)) 19. System.out.print(obj + “,”); 20. } ‘What is the result?

  1. 3,2, 1,

  2. 1, 2, 3,

  3. Compilation fails.

  4. The code runs with no output.

  5. An exception is thrown at runtime.


Correct Option: C
Explanation:

The correct answer is C. Compilation fails.

The code will fail to compile at line 18 because the for loop cannot iterate over an iterator. The reverse() method returns an iterator, but the for loop expects an object.

To fix the code, you can either change the for loop to a while loop, or you can return a list from the reverse() method.

public static List reverse(List list) {
  Collections.reverse(list);
  return list;
}

With this change, the code will compile and run successfully, and the output will be 3, 2, 1.

Here is an explanation of each option:

  • Option A: This option is incorrect because the for loop cannot iterate over an iterator. The reverse() method returns an iterator, but the for loop expects an object.
  • Option B: This option is incorrect because the code will not run. The for loop will fail to compile at line 18.
  • Option C: This option is correct because the code will fail to compile at line 18.
  • Option D: This option is incorrect because the code will not run. The for loop will fail to compile at line 18.
  • Option E: This option is incorrect because no exception will be thrown at runtime. The code will simply fail to compile.

Find more quizzes: