A static block of a class executes at class load time, executes earlier than the constructor, and executes only once.
The following example can help to understand:
1 Packageuntility;2 3 Public classA {4 //static Block5 Static {6 A C;7SYSTEM.OUT.PRINTLN (200);8c =NewA ();9i = 10;Ten } One A Public Static inti; - Public intJ; - the PublicA () { - System.out.println (A.I); - System.out.println (j); - } + - Public Static voidMain (string[] args) { +A A =NULL; ASYSTEM.OUT.PRINTLN (100); atA =NewA (); - //a B = new A (); - } -}
Operation Result:
20000100100
Analytical:
The program goes in from the main method, executes to 21 lines of code to load the class, then executes the static module, proceeds to line 6th, loads the class again, runs to the static module again, and the 6th line has been executed once, so it is no longer executed (After writing the Java class static block two found here the description is problematic, here will not be repeated loading Class A, will only repeat the 7th row), and then execute line 7th, so the first is printed out is 200, and then execute the 8th sentence of the constructor (not executed to the 9th sentence, so I and J are 0), Print out 2 0, then proceed to the 9th sentence in the static module, at this time i=10, to this load class complete, and then continue to execute 21 lines of the =null statement, in the execution of 22 lines of print, output 100, and finally execute the 23rd row of the constructor, printed out 10 0 (because I is static).
Static block of Java class