ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

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() { System.out.print("6"); }
}
// in main:
new C();
new C();
  1. A. 1423562356
  2. B. 1234562356
  3. C. 142356142356
  4. D. 1425362536

Correct answer: A. 1423562356

Class initialisation runs once, parent first: 1, 4. Each new C() then runs P's instance initialiser and constructor (2, 3) before C's (5, 6). The second object repeats only the instance part: 2356.

More OOP with C++ and Java questions

Exams that ask this topic