ProgrammingHardTCS NQT · Infosys · Accenture
What does this Java program print? class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } } class C extends P { static { System.out.print("4"); } { System.out.print("5"); } C() { System.out.print("6"); } } // in main: new C(); new C();
- A. 142356142356
- B. 1423562356
- C. 1234562356
- D. 1243562356
Correct answer: B. 1423562356
Static blocks run once, when the class is initialised, superclass first: 1 then 4. Each new C then runs the superclass instance initialiser and constructor (2, 3) before the subclass's (5, 6), so the second object adds only 2356.
More OOP with C++ and Java questions
- What does this Java program print? static int f() { int x = 1; try { return x; } finally { x = 3; } } static int g() { try { throw new…
- What does this C++ program print? struct B { B() { f(); } virtual void f() { std::cout << "B"; } }; struct D : B { D() { f(); } void f()…
- What does this C++ program print? struct B { virtual void f(int x = 1) { std::cout << "B" << x; } }; struct D : B { void f(int x = 2)…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout <<…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct T { T() { cout << "T"; } ~T() { cout << "~"; } }; void g()…