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);- A. 1 1 2
- B. 2 2 2
- C. 1 2 2
- 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
- What is printed? cpp struct Base { void who() { cout << "Base"; } }; struct Derived : Base { void who() { cout << "Derived"; } }; int…
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? cpp struct Animal { void speak() { cout << "..."; } }; struct Dog : Animal { void speak() { cout << "Woof"; } }; int…
- What is printed? (function-local static) cpp int next() { static int n = 0; return ++n; } int main() { cout << next() << next() << next()…
- What is printed? java class A { void greet() { System.out.print("A-inst "); } static void greet(int x) { System.out.print("A-static "); }…
- What is printed? cpp class Base { public: void info() { cout << "Base::info "; helper(); } void helper() { cout << "Base::helper"; } }…