Given: class Bird { { System.out.print("bl "); } public Bird() { System.out.print("b2 "); } } class Raptor extends Bird { static { System.out.print("r1 "); } public Raptor() { System.out.print("r2 "); } { System.out.print("r3 "); } static { System.out.print("r4 "); } } class Hawk extends Raptor { public static void main(String[] args) { System.out.print("pre "); new Hawk(); System.out.println("hawk "); } } What is the result?

  1. pre b1 b2 r3 r2 hawk

  2. pre b2 b1 r2 r3 hawk

  3. pre b2 b1 r2 r3 hawk r1 r4

  4. r1 r4 pre b1 b2 r3 r2 hawk

  5. r1 r4 pre b2 b1 r2 r3 hawk

  6. Compilation fails.


Correct Option: D

AI Explanation

To answer this question, let's go through the code step by step:

  1. We start by executing the main method in the Hawk class.
  2. The first line in the main method is System.out.print("pre ");, which prints "pre ".
  3. The next line is new Hawk();, which creates a new instance of the Hawk class.
  4. Since Hawk extends Raptor, which extends Bird, the first thing that happens when we create a new instance of Hawk is the execution of the Bird constructor.
  5. The Bird constructor contains an instance initializer block, which prints "bl ".
  6. Then, the Bird constructor itself prints "b2 ".
  7. After the Bird constructor is executed, we move on to the Raptor constructor.
  8. Before the Raptor constructor, there is a static initializer block, which prints "r1 ".
  9. Then, the Raptor constructor itself prints "r2 ".
  10. Next, there is another instance initializer block in the Raptor class, which prints "r3 ".
  11. Finally, there is another static initializer block in the Raptor class, which prints "r4 ".
  12. After the Raptor constructor is executed, we move back to the Hawk constructor.
  13. Since there are no instance initializer blocks in the Hawk class, we move directly to the Hawk constructor, which does not contain any print statements.
  14. After the Hawk constructor is executed, we go back to the main method.
  15. The last line in the main method is System.out.println("hawk ");, which prints "hawk ".

Based on the above explanation, the result will be:

D. r1 r4 pre b1 b2 r3 r2 hawk

Find more quizzes: