Originally posted by ramya jp: in which static block is executed first than then the static variable.[/QB]
What makes you think that the static block is executing prior to the static variable initialization.
As you can see from my sample app above, static variable initializers and blocks are executed from top to bottom, in order to definition. It works the same way in your application.
Instance variable initializers/instance initializer blocks work the same way - executed from top to bottom.
Here's the order of execution...
1. When the class is loaded, static initializers are executed from top to bottom. 2. When the class is instantiated, there are a couple steps... 2a. First, all instance initializers are executed from top to bottom. 2b. Second, the constructor is executed. (Note that the first step of the constructor is to invoke the parent class' constructor).
Originally posted by ramya jp: Corey the output is 1 null Starting main 3 null Ending main
This mean the order of execution is from top to bottom,am i right.If so what is confussing me is in the below program
the output is this is static In A.main,B.y=22
in which static block is executed first than then the static variable.
Kindly explain this to me
That's not quite true. The static variable is getting created first in Class B before the static initializer code is run. You just print the value of the static variable in class Call which happens after B is done.
In you code you have
in that static initializer code and you will get 22 printed out.
2b. Second, the constructor is executed. (Note that the first step of the constructor is to invoke the parent class' constructor).
Actually, the first line of a constructor (super(...) or this(...)) is executed before step 2a, before any instance initializers have been run or even varables set to default values, in the current class or any super classes. At this point, the instance barely exists.
That is the reason for these restrictions on the arguments to a constructor call on the first line of a constructor:
From JLS 18.104.22.168 An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.