ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Counter {
    static int count = 0;
    Counter() { count++; }
}
// in main:
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(c1.count + " " + c2.count + " " + Counter.count);
  1. A. 1 1 2
  2. B. 2 2 2
  3. C. 1 2 2
  4. D. 0 1 2

Correct answer: B. 2 2 2

count is a single static field shared by the class, not per-instance. Accessing it through c1 or c2 is just syntactic sugar that still reads the one shared field, which is 2 after both constructors ran; Counter.count reads the same field.

More OOP with C++ and Java questions

Exams that ask this topic