First you are assigning value to variable i in a static block,which is invoked when the class is first loaded. Then when you create an instance of the class, the variable i which is for that instance is assigned the value 20,at the time of instance creation the static block is not invoked(like I said it's invoked only once when the class is loaded). Hence the answer 20....
The output of 20 is correct. You need to understand in this program that there are two variables 'i' with the same name. one is an instance variable(int i=20) and the other is a local variable (scope limited to the static block). Now in the main method an instance of class is created and using that instance the variable i is accessed and hence the value is 20.
The variable i declared in the static block cannot be accessed from the main method because of its limited scope. You can modify the above program as:
Now the output will be 10 because the scope of variable j is now extended and it can be accessed anywhere within the same package.
Now we have two assignments for the same static variable i. Why is the assignment in the static block comes second? Does the declaration of the class triggers first the i=10 assigment and then the static block?
Hi Bob, the static block is reached last because all field initializers and initialization blocks are executed in the order in which they occur in the class declaration. Also, a variable can be declared after they are initialized (if the last occurs in a block), . So the below two snippets compile and run, although they produces different outputs:
The same is true for instance (non-static) variables. However the follow don't compile:
this should produce the output of 5 instead of 10 and the order should not matter should it?
Aside, I vaguely remember that some variable will be assigned a value after the constructor is called,
is the following flow correct when you create a new trial object?
1) give i a default value 0
2) run the constuctor
3) assign 5 to i since constructor does not initialize i
sounds weird to myself
However, a similar thing happens with non static members.So while your code
j=10; --> compiler error
int j=5;
is giving a compile error, this would not :
{
j=10;
}
int j=5; //after an object is created, initialize j, set its value to 10, then again set j to 5 (before running its constructor)