From: http://www.cnblogs.com/o-andy-o/archive/2011/12/28/2304959.html
The static block is executed only once when the class is loaded.
Class usestatic {
Static int A = 3;
Static int B;
Static void meth (int x ){
System. out. println ("x =" + x); system. out. println ("A =" + a); system. out. println ("B =" + B );
}
Static {
System. Out. println ("static block initialized .");
B = A * 4;
}
Public static void main (string ARGs []) {
Meth (42 );
}
}
Once the usestatic class is loaded, all static statements are run. First, a is set to 3, then the static block is executed (print a message), and finally, B is initialized to a * 4 or 12. Then, call main () and main () to call meth () and pass the value 42 to X. The three println () Statements reference two static variables A and B, and the local variable X. Note: It is invalid to reference any instance variable in a static method. Below isProgramOutput:
Static block initialized.
X = 42
A = 3
B = 12
One step at a time to facilitate your review
The static block is executed only once when the class is loaded.
Class usestatic {
Static int A = 3;
Static int B;
Static void meth (int x ){
System. out. println ("x =" + x); system. out. println ("A =" + a); system. out. println ("B =" + B );
}
Static {
System. Out. println ("static block initialized .");
B = A * 4;
}
Public static void main (string ARGs []) {
Meth (42 );
}
}
Once the usestatic class is loaded, all static statements are run. First, a is set to 3, then the static block is executed (print a message), and finally, B is initialized to a * 4 or 12. Then, call main () and main () to call meth () and pass the value 42 to X. The three println () Statements reference two static variables A and B, and the local variable X. Note: It is invalid to reference any instance variable in a static method. The output of the program is as follows:
Static block initialized.
X = 42
A = 3
B = 12