Okay ... I think when the java would be executing the initilazers from top to bottom , in second case when it would be doing so , it first has to run the test1() method so so i gets its value ..
but in first case when the java would be executing the initializers , it doesn't need to run j as such as j is a literal ..but then java would already have first saved all the static members values before executing initializers .. so then i shoud have got the j value which was save to 0 by default.
Plz help me in clearing this concept.
1 person found this helpful
Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
Because the implementors of Java intentionally chose to do it that way.
There are TWO stages to the process: preparation (which occurs first) and initialization.
See the Java Language Spec section 12.4.1 'When Initialization Occurs
The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§22.214.171.124). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
Then if you check that referenced section 126.96.36.199 you will find this
The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively
static) field of a class or interface C and all of the following conditions hold:
When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'.