ProgrammingModerateProduct-company placement · Java

What is printed?

What is printed?
class Range implements Iterable<Integer> {
    public Iterator<Integer> iterator() { return List.of(1, 2, 3).iterator(); }
}
// in main:
for (int x : new Range()) System.out.print(x);
  1. A. Compile-time error: Range is not a collection
  2. B. [1, 2, 3]
  3. C. 123
  4. D. 321

Correct answer: C. 123

The enhanced for loop works with any Iterable: it calls iterator() and then hasNext/next, unboxing each Integer into x.

More OOP with C++ and Java questions

Exams that ask this topic