I have created the following experimental code to clarify my ideas
The output from the code is 2 and 2. I expected it to be 4 and 4 on the basis that the declaration of i will be found first and then the value will be set to 4 at the time of class load. However, if I change the order of my initialization so that the initialization line becomes my first line in the class (ie make line 6 line 2) then the output changes to 4 and 4. It is as if the two static initialization of i are happening in two separate initialization blocks. Why does this happen?
That is how it is defined in the specification. Static initializers, and initialization of static variables, are done in the order that they are encountered in the java source.
Rajeev Trikha wrote:I expected it to be 4 and 4 on the basis that the declaration of i will be found first and then the value will be set to 4 at the time of class load.
Declaration and initialization are not the same thing.
That is how it is defined in the specification. Static initializers, and initialization of static variables, are done in the order that they are encountered in the java source.
This satisfies my curiosity.
Thanks for the other inputs too as they further clarified the idea.
So is this the correct initialization order: 1) statics from top-to-bottom, both
declarations & code blocks, 2) non-static declarations with initial values, from
top-to-bottom and finally, 3) the non-static code blocks, once more from
top-to-bottom?
Jim ... ... (Sorry for late post. I've been gone.)
Which shows that after executing the constructor of the super class the object initialisation blocks and initializers take place in top-to-down order. However, if I stick {int i=4} then this i variable value will be lost because of the local scope.
Rajeev Trikha (SCJP 6)
He loves you so much! And I'm baking the cake! I'm going to put this tiny ad in the cake:
a bit of art, as a gift, the permaculture playing cards