In the first example, the compiler is confused as to what 'a' variable you are referring to. It thinks you are referring to a local variable, but no local variable 'a' has been defined yet. This is the same behavior you would see if this code was inside a method.
You can make this code work by being explicit about what 'a' you are referencing:
In the second example, the method doIt() has not defined a local variable 'a' but the method has visibility to the class-level fields. So the compiler assumes you are referencing the 'a' at the class-level.
doIt() executes when the class is loaded because it's called from a class-level static block. It returns 0 because the code to initialize 'a' has not been executed yet when doIt() is called and 0 is the default value for an int. [ November 23, 2006: Message edited by: Scott Johnson ]
Joined: Nov 05, 2006
Hi Scot. I still don't understand. How come the method has visibility to the variable but initialization block doesnt? Also, when I write
The code compiles normally? Why does the order matter?