ProgrammingModerateWipro · Capgemini pattern

What is printed?

What is printed?
class C {
    static int n = 0;
    C() { n++; }
}
// in main:
for (int i = 0; i < 3; i++) new C();
C c = new C();
System.out.print(c.n);
  1. A. 3
  2. B. 1
  3. C. 4
  4. D. 0

Correct answer: C. 4

n is static, so one copy is shared by all objects and every constructor call adds to it: 3 objects in the loop plus c makes 4. Reading it through c.n still reads the shared field.

More OOP with C++ and Java questions

Exams that ask this topic