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 6then2 3 5 61 2 3 4 5 6then1 2 3 4 5 64 1 5 2 6 3then5 2 6 31 4 2 5 3 6then2 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.