code block
----A static code block
----B Construction code block
----C Common code block
Execution order: (Priority from high to low.) Static code block >mian method > construct code block > Construct method.
A. Static code block:
A static code block executes when the class is loaded and executes only once!
1 classtest{2 Public Static voidMain (String args[])3 {4Demo d1=NewDemo ();D emo d2=NewDemo ();5 6 }7 }8 9 classdemo{Ten Static{ OneSystem.out.println ("This is a static block of code, see how many times I will perform"); A } - } - the - //Run Results -This is a static code block, see how many times I will perform
B. Constructing code blocks, execution order greater than construction methods
B.1.java when a compiler builds a Java file, it moves the variable declaration to the front of a class.
The initialization of member variables in B.2.java is actually performed in constructors.
When the B.3.java compiler compiles, the code in the construction code block is moved to the constructor, and the method in the original constructor is executed at the end. (Demo2 runs without errors, proves this, and can be deserialized)
B.4. The display of member variables is initialized and code in the construction code block is executed in the order of the Code. (Compare Demo3 and Demo4)
Main function
public class Test{public static void Main (string[] args) {demo d=new demo (); System.out.println (D.I);}} //Demo1//Execution result I=30000;public class Demo { int i=10000; { i=20000; } Public Demo () { i=30000; }} //Demo2//Execution result I=30000;public class Demo { { i=20000; } Public Demo () { i=30000; } int i=10000;} //Demo3//Execution result I=10000;public class Demo { { i=20000; } Public Demo () {// i=30000; } int i=10000;} //Demo4//Execution result I=20000;public class Demo { int i=10000; { i=20000; } Public Demo () {// i=30000; }}
Common code block, the only function is to let the variable resources inside as soon as possible to be released
Common code blocks
publicclass test{ publicstaticvoid main (string[] args) { { System.out.println ("I am an ordinary code block");} }
}
Building blocks of code in Java