1. Java organizes multiple static initialization actions into a special "static clause", which is a static block.
2. the initialization code in the static block will be executed together.
Public class staticbolck1 {// static block static {staticbolck1 A = new staticbolck1 (); I = 10;} public static int I; Public Int J; Public staticbolck1 () {system. out. println ("= 1111 ="); system. out. println (staticbolck1. I); system. out. println ("= 2222 ="); system. out. println (j); system. out. println ("= END =");} public static void main (string [] ARGs) {staticbolck1 A = new staticbolck1 ();}}
Output:
= 1111 =
0
= 2222 =
0
=== End ====
= 1111 =
10
= 2222 =
0
=== End =
Note:
The static module is first loaded and only loaded once during class loading, and the constructor can load the module multiple times.
The loading sequence is static module and constructor.
In the main method (program entry) main method, new A (); so static {} is loaded {}.
New A is added again in static, so its constructor is called public (){},
At this time, the printed content is I = 0 J = 0, both of which are initialized values.
After the static module is loaded, it loads its constructor.
In this case, the value of I in static is 10 and J remains unchanged. Therefore, I = 10 J = 0 is printed in the second call of the constructor.
In addition, there is a usage in Java called "non-static block", which has the same function and initialization sequence as "static block.
The only difference is that "non-static block" is not static and does not have the static keyword.