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();

  1. A. 142356142356
  2. B. 1423562356
  3. C. 1234562356
  4. 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

Exams that ask this topic