The static{} (that is, the static block) is executed at the time the class is loaded and is executed only once, typically to initialize static variables and invoke static methods, and we discuss in detail the characteristics and applications of the block.
First, the contents of the static{} statement block are only executed once during the execution of a program, and look at the following example:
Example One
Java code class test{ public static int x=100; public final static int y;=200 public test () { system.out.println ("Test constructor execution"); } static{         SYSTEM.OUT.PRINTLN ("Static statement Block execution"); } public static void display () { system.out.println (" Static method is executed "); } Public void&nbsP;display_1 () { system.out.println (" Instance method is executed "); } } public class staticblocktest{ public static void main (string args[]) { try{ class.forname ("Test"); Class.forName ("Test"); }catch ( Classnotfoundexception e) { e.printstacktracE (); } } }
Results: You will find that although two class.forname ("Test") statements are executed, only one "static method is executed" statement is exported; the second class.forname () statement is not valid because a class is only loaded once in the life cycle of the virtual machine And because static{} is executed with the class load, the static{} is executed only once, no matter how many instances of the object you are new. -- about class loading see the Appendix to this article.
Second, the static{} statement block execution timing (in fact, the appendix in the class loading time)
It says that static{} will execute when the class is loaded, we must understand exactly what the class load is meant to be:
1, with Class.forName () display loading, such as the above example one;
2, when instantiating a class, if you change the contents of the main () function to: Test t=new test ();//This form actually compares with 1, the principle is the same, both are displayed loading this class, the reader can verify test t=new test (); and test t= (test) Class.forName (). newinstance (); These two statements have the same effect.
3, when calling the static method of the class, such as the contents of the main () function, change to: Test.display ();
4, when calling the class static variables, such as the contents of the main () function to: System.out.println (test.x);
in general, these four kinds of situations, but we particularly need to pay attention to two points:
1, when calling the class static constants, it will not load the class, that is, do not execute static{} statement block, the reader can verify their own (the main () function of the contents of the SYSTEM.OUT.PRINTLN (TEST.Y);), you will find that the program only output a 200; This is the rule of the Java Virtual machine, when accessing static constants of a class, if the compiler can calculate the value of a constant, the class will not be loaded, or the class will be loaded.
2, in the form of Class.forName (), we can also set ourselves to do not load the class, such as the Class.forName ("test") to Class.forName ("test", false, StaticBlockTest.class.getClassLoader ()), you will find that the program has no output, that is, test is not loaded, static{} is not executed.
Three, static{} statement block execution order
1, when there are multiple static{} in a class, in accordance with the static{} defined order, from the after the implementation;
2, the first execution of static{} statement block content, will execute the call statement;
Example Two
Java code public class teststatic{ static{         SYSTEM.OUT.PRINTLN (1); } static { SYSTEM.OUT.PRINTLN (2); } static { system.out.println (3); } public static void main (string args[]) { system.out.println (5); } static {   SYSTEM.OUT.PRINTLN (4); } }
result : The program will output 1,2,3,4,5
3. If the static variable is assigned an initial value (such as a static int x=100) when it is defined, the assignment is also done when the class is loaded, and when a class has both static{and static variables, it follows the principle of "first definition first execution";
example Three
Java code class test{public static int x=300; static{System.out.println (X); x=200; System.out.println (X); The public class staticblocktest{public static void Main (String args[]) {System.out.println (test.x); } }
Results: The program will output 300,200,200 sequentially, execute the x=300 first, and then execute the static{} statement block.
Four, static{} statement block application
1, the application of JDBC
Readers familiar with JDBC should know that there is a DriverManager class in Java that manages various database drivers and creates new database connections. The DriverManager class contains column drivers classes that must register themselves by calling the DriverManager Registerdriver () method, and when did the registration occur. Here are the answers:
All drivers classes must contain a static method that allows you to create an instance of the class and then register it with the Drivermanage class when the instance is loaded. We often use Class.forName () to load the driver, then the registration occurs in the execution of this statement, the previous drivers static method is placed in static{}, when the driver is loaded, will execute the static{}, The registration is completed.
2, the application of Hibernate
The sessionfactory in Hibernate is a heavyweight class, and creating an object instance of that class consumes a lot of system resources, and if you create an instance of that class every time you need it, it is obvious that the execution of the class will be reduced, so you often put the instantiation of that type in a static{} , you can improve the execution efficiency of the program by simply executing it on the first call, as follows: Java code static {try {configuration.configure (configfile); Sessionfactory = Configuration.buildsessionfactory (); catch (Exception e) {System.err.println ("%%%% Error creating Sessionfactory%%%%"); E.printstacktrace (); } }
V. Appendix
class Loading: The function of Java commands is to start the virtual machine, the virtual machine through the input stream, from the disk in the bytecode file (. class file) Read the contents of the virtual machine, and save the process is class loading.
The
class loads attribute :
* A class is only loaded once in the life cycle of the virtual machine.
* class loading principle: lazy loading, less load, because the virtual machine space is limited.
* class loading time:
1 The first time you create an object to load the class.
2) to load a class when calling a static method, the class is loaded when the static property is accessed.
3) loading a subclass is bound to load the parent class first.
4) Create object references do not load classes.
5) Subclasses call the static method of the parent class
(1) When a subclass does not override a static method of the parent class, only the parent class is loaded, and the subclass
(2) is not loaded when the subclass has a static method that overrides the parent class, the parent class is loaded. Loading a subclass
6) accesses a static constant, and if the compiler can calculate the value of a constant, the class is not loaded, for example: public static final int a = 123; Otherwise, the class is loaded, for example: public static final int a = Math. Pi.