Skip to content
CodeKruPro

Order of static blocks, instance blocks and constructors

QuizMediumJava onlyAsked in: Accenture, Infosys, TCS, Wipro

A static block runs once when the class is first used. A plain { ... } block in the class body (an instance block) runs for every new object. What does this print?

class Base {
    static { System.out.print("1 "); }
    { System.out.print("2 "); }
    Base() { System.out.print("3 "); }
}
class Child extends Base {
    static { System.out.print("4 "); }
    { System.out.print("5 "); }
    Child() { System.out.print("6 "); }
}
// in main:
new Child();
System.out.println();
new Child();
  • 1 4 2 3 5 6 then 2 3 5 6
  • 1 2 3 4 5 6 then 1 2 3 4 5 6
  • 4 1 5 2 6 3 then 5 2 6 3
  • 1 4 2 5 3 6 then 2 5 3 6

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in