InterviewSolution
| 1. |
What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code? |
|
Answer» class InterviewBit{ INT i; static int J; { System.out.println(" Instance Block 1. Value of i = "+i); } static{ System.out.println(" Static Block 1. Value of j = "+j); method_2(); } { i = 5; } static{ j = 10; } InterviewBit(){ System.out.println(" Welcome to InterviewBit "); } public static void main(String[] args){ InterviewBit ib = new InterviewBit(); } public void method_1(){ System.out.println(" Instance method. "); } static{ System.out.println(" Static Block 2. Value of j = "+j); } { System.out.println(" Instance Block 2. Value of i = "+i); method_1(); } public static void method_2(){ System.out.println(" Static method. "); }} The Output we get by executing this program will be Static Block 1. Value of j = 0 This is a java tricky interview question frequently asked in java interviews for the EXPERIENCED. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are -
In above steps from 4 to 6, will be executed for EVERY object creation. If we create multiple objects then for every object these steps will be performed. Now from the above code, the execution will happen like this - 1. In the step of identification of static members. It is found that -
During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned. 2. In the next step, it will execute the static block and assign the value in static variables.
3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of INSTANCES will happen. 4. Identify the instance variables and blocks from top to bottom.
Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly. 5. It will execute the instance methods and assign the original value to the instance variable.
6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor. This is how the java program gets executed. |
|