ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
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() { this(0); System.out.print("6"); }
    C(int k) { System.out.print("7"); }
}
// in main:
new C();
new C();
  1. A. 142357623576
  2. B. 14235576235576
  3. C. 142376523765
  4. D. 14235761423576

Correct answer: A. 142357623576

Static initialisers run once, when each class is first initialised, parent first: 1 then 4. For each object, C() begins with this(0), so it does not call super itself; C(int) does (implicitly). Instance initialisers of C run right after the super() call, i.e. only inside C(int). So each object prints P's initialiser 2, P() 3, C's initialiser 5, C(int) 7, and finally the rest of C() 6: 23576. Running the initialiser in both constructors gives 5 twice; repeating the static blocks for the second object is the other trap.

More OOP with C++ and Java questions

Exams that ask this topic