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();
}
}- A. open:R0 open:R1 use:R0 use:R1
- B. use:R0 use:R1 open:R0 open:R1
- C. open:R0 use:R0 open:R1 use:R1
- 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
- What is printed? cpp class Base { public: Base() { cout << "Base() "; } Base(int x) : Base() { cout << "Base(int) "; } }; int main() {…
- What is printed? java class Counter { int value; Counter(int v) { value = v; } Counter increment() { return new Counter(value + 1); }…
- What is printed? cpp struct Animal { virtual ~Animal() {} virtual void speak() const { cout << "..."; } }; struct Dog : Animal { void…
- What is printed? java class A { A() { System.out.print(id() + " "); } int id() { return 0; } } class B extends A { int val; B(int v) { val…
- What is printed? cpp struct Shape { virtual void draw() const { cout << "Shape "; } }; struct Group : Shape { std::vector<Shape> children…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; } }; struct C : B {…