0
What's output ??
I saw it in quiz but I don't understand why the answer is 2 ,it have two static initialization block but no object created to use them https://code.sololearn.com/cY3Il5AqQhyD/?ref=app
4 Answers
+ 2
The quiz wants to test your knowledge on execution order.
Before main function is executed, all static variables and static blocks are executed.
First static variables are defined and then static blocks are executed:
static int i;
static {i=0;}
static{i=2;}
Then main function is executed:
System.out.print(i); // prints 2
And i is set to 1:
i=1;
+ 3
For static block no need to create object. When your application runs static first store in JVM. So here we have two static block but last static block will store in last and value of i will be assign to 2 so that's why answer is 2.
We can also call static method without creating the object of class.
+ 3
Static blocks are executed when the class is loaded to memory, and they are run in the same order as they appear in the code.
In your example, the value of i is determined by the last static block (i=2) then the main function prints this value.
Read more examples here:
https://beginnersbook.com/2013/04/java-static-class-block-methods-variables/
+ 1
Thank u very much , fully understood