What is the output for the below code ? class A { { System.out.print("b1 "); } public A() { System.out.print("b2 "); } } class B extends A { static { System.out.print("r1 "); } public B() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class C extends B { public static void main(String[] args) { System.out.print("pre "); new C(); System.out.println("post "); } }

  1. r1 r4 pre b1 b2 r3 r2 post

  2. r1 r4 pre b1 b2 post

  3. r1 r4 pre b1 b2 post r3 r2

  4. pre r1 r4 b1 b2 r2 r3 post


Correct Option: A
Explanation:

To understand the output of the given code, the user needs to know about the order of initialization of static and non-static blocks, constructors, and the concept of inheritance.

When the main method is executed, the following sequence of events will occur:

  1. The static block of class B will be executed first. It will print "r1 r4".

  2. The static block of class C will not be executed because it is not defined.

  3. The print statement inside the main method will execute and print "pre".

  4. A new object of class C is created using the default constructor.

  5. Since class C extends class B, the constructor of class B will be called first.

  6. Before the constructor of class B is called, the non-static block of class A will be executed. It will print "b1".

  7. The constructor of class B will be executed next. It will print "b2" and "r2".

  8. Before the constructor of class C is called, the non-static block of class B will be executed. It will print "r3".

  9. The constructor of class C will be executed last. It will not print anything.

  10. After the constructor of class C is called, the print statement inside the main method will execute and print "post".

Therefore, the output will be:

The Answer is: A) r1 r4 pre b1 b2 r3 r2 post

Find more quizzes: