ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Resource {
    String name;
    Resource(String n) { name = n; System.out.print("open:" + n + " "); }
    void use() { System.out.print("use:" + name + " "); }
}
public class Main {
    public static void main(String[] args) {
        Resource[] pool = new Resource[2];
        for (int i = 0; i < 2; i++) {
            pool[i] = new Resource("R" + i);
        }
        for (Resource r : pool) r.use();
    }
}
  1. A. open:R0 open:R1 use:R0 use:R1
  2. B. use:R0 use:R1 open:R0 open:R1
  3. C. open:R0 use:R0 open:R1 use:R1
  4. D. Compile-time error: pool[i] cannot be assigned inside a for loop

Correct answer: A. open:R0 open:R1 use:R0 use:R1

The first loop fully populates the array, constructing R0 then R1 (printing open:R0 open:R1). Only the second, separate loop then calls use() on each already-constructed element in array order, printing use:R0 use:R1.

More OOP with C++ and Java questions

Exams that ask this topic