Here is the complete code from the book
Oracle Certified Assosciate Java SE 8 Programmer 1 Study Guide By Jeanne Boyarsky and Scott Selikof
Then authors modified some initial lines to:
Well What they really means for the order is: just after when the new operator is invoked on the class the construction process for an object starts, where the initialization and instance initializer blocks are executed first in the order they are written. so in the first case where the code compiles, the variable
name is initialized before the instance initializer block and thus if we try to access the variable further it will be the value with which it was initialized. however in the next case the instance initializer block will execute first where it is trying to access the variable which is not even declared(or initialized) yet so the compiler will remind us for this(compiler really tries its best to caught some mistakes as early as possible).
For MAIN: yes the code starts right there but when it sees the new is invoked on the constructor, it gets the type of the object it needs to construct and thus before calling the constructor there are some setups applied on the object being constructed like the case we see.
[EDIT]: I will give you some more examples of those setups, but lets see some more code and try to guess it's output:
Here is the output:
When you give the command(after successful compilation) for running the code:
Java Chick.
Here are the things that will happen:
Before the invocation of main the class will be loaded(in which main is defined).Loading a class causes the initialization of class variables and static initializer blocks to run in the order they are encountered from top to bottom in class.Please note the static initilaizers(if any) in the super class will be executed before the child class.During execution of one of the static initializer blocks i have created an instance variable inside it, which will cause the execution of instance initializer blocks and instance variable initialization. thereafter the constructor call will execute.Please note: i have called the instance method hello() inside the instance initializer block which is executed before the construcor() which means the dynamic binding of methods with the object is happening before the constructor completes.Notice the value of static variable i, which is printed twice in static initializer block, and think about, why the value 0 and 1 is printed.
If you are interested to dig deep in this topic here is the reference to the appropriate section in Java Language Specification:
Execution.
Praveen