Static and non-static code blocks in Java
Static code block:
Static {}
The execution priority is higher than that of non-static initialization blocks. It will be executed once when the object is loaded to the system and destroyed after the execution is complete. It can only initialize class variables, that is, static modified data members.
Non-static code block:
{}
If a static initialization block exists during execution, the static initialization block is executed first and then the non-static initialization block is executed. Each object is executed once and can initialize instance variables of the class. Non-static initialization blocks are run before the main code of the constructor is executed during the constructor execution.
Routine:
Public class Test1 {public static String staticField = "static variable"; public String field = "variable"; static {System. out. println (staticField); System. out. println ("static initial block");} {System. out. println (field); System. out. println ("initialization block");} public Test1 () {System. out. println ("constructor");} public static void main (String [] args) {new Test1 (); System. out. println (); new Test1 ();}}
Routine running result:
Static variables
Static initial block
Variable
Initialization Block
Constructor
Variable
Initialization Block
Constructor