On page 203 in the book 'Certified Associate Java SE 8 Programmer I' by Jeanne Boyarsky and Scott Selikoff, there is a code sample that is supposed to give output based on the order of initialization:
To my understanding, the order of initialization is:
2. static variables
3. instance variables
4. the constructor
However, the output from the code above is: 1
I'm the statement before creating a new InitializationOrder object.
Why does the print statement for the static variable on line 11 print before the output statement on line 17? The initialization wasn't invoked until line 18.
In other words, why wasn't the output: I'm the statement before creating a new InitializationOrder object.
Sam Peterson wrote:The initialization wasn't invoked until line 18.
Not so. Your class is named InitializationOrder and so the class is loaded before its static main(String...) method can be run. And as part of loading the class, its static initializers are run before anything else happens. The block including line 11 is a static initializer.
What happens at line 18 is that an instance of the class InitializationOrder is created (via a constructor). At that point the constructor and the instance initializers are run, in some order which this example is supposed to be teaching you.