static{} clause block in Java

Source: Internet
Author: User
Tags instance method

static{} (that is, the static block), will be executed when the class is loaded and will only be executed once , generally used to initialize static variables and call static methods, the following is a detailed discussion of the statement block characteristics and application.

First, during the execution of a program, the contents of the static{} statement block are only executed once, as shown in the following example:

Example One

classtest{ Public Static intx=100;  Public Final Static inty;=200 PublicTest () {System.out.println ("Test constructor Execution"); }      Static{System.out.println ("Static statement block Execution"); }       Public Static voiddisplay () {System.out.println ("Static method is executed"); }       Public voiddisplay_1 () {System.out.println ("Instance method is executed"); }  }   Public classstaticblocktest{ Public Static voidMain (String args[]) {Try{class.forname ("Test"); Class.forName ("Test"); }Catch(ClassNotFoundException e) {e.printstacktrace (); }                  }     }  

result : You will find that although two class.forname ("Test") statements are executed, only one "static method executed" statement is output, but the second class.forname () statement is invalid because A class is only loaded once during the lifetime of the virtual machine , and because static{} is executed with class loading, no matter how many times the object instance is new, static{} is executed only once. --See The Appendix to this article for class loading.

Second, static{} statement block execution time (in fact, the time of class loading in the appendix)

It says that static{} will be executed when the class is loaded, and we must understand exactly what the class load means, meaning the following:

1, with Class.forName () display when loading, such as the above example one;

2, when instantiating a class, such as the main () function to change the contents of: Test t=new Test ();//This form actually compared with 1, the principle is the same, is the display of loading this class, the reader can verify the test t=new test (); and test t= (test) Class.forName (). newinstance (); These two statements have the same effect.

3, call the static method of the class, such as the main () function to change the contents of: Test.display ();

4, call the static variables of the class, such as the main () function to change the contents of: System.out.println (test.x);

In general, there are four cases, but we need to pay attention to two points in particular:

1, call the static constant of the class, will not load the class, that is, do not execute static{} statement block, the reader can verify their own (the main () function to change 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 the static constants of a class, if the compiler can calculate the value of a constant, the class will not load, otherwise the class will be loaded)

2, in the form of Class.forName (), we can also set their own 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.

Third, static{} statement block execution order

1 , when a class has more than static{}, according to static{} in the order of definition, from the go after execution;

2, execute the call statement only after executing the contents of the static{} statement block;

Example Two

 Public classteststatic{Static{System.out.println (1); }    Static{System.out.println (2); }    Static{System.out.println (3); }     Public Static voidMain (String args[]) {System.out.println (5); }    Static{System.out.println (4); }}

result : The program will output 1,2,3,4,5

3. If a static variable is assigned an initial value (such as a static int x=100) at the time of definition, then the assignment is done at the time the class is loaded, and when a class has both static{} and a static variable, it also follows the "define first" 's Principles;

Example Three

Classpublicstaticint x=300static{  System.out.println (X);  X=200;  System.out.println (X); }}publicclasspublicstaticvoid  Main (String args[]) {  System.out.println (test.x);}}

result : The program outputs 300,200,200 sequentially, executes the x=300 first, and then executes the static{} statement block.

Four, static{} statement block application

1. Application in JDBC

Readers familiar with JDBC should know that there is a DriverManager class in Java that manages various database drivers and establishes new database connections. The DriverManager class contains some column drivers classes that must register themselves by invoking the Registerdriver () method of DriverManager, so when does registration occur? Here are the answers:

All drivers classes must contain a static method that can be used to create an instance of the class and then register with the Drivermanage class when the instance is loaded. We often use Class.forName () to load the driver, then the registration occurs during the execution of this statement, the previous drivers static method is placed in the static{}, when the driver is loaded, the static{} is executed, Completed the registration.

2, hibernate in the application

Hibernate Sessionfactory is a heavyweight class, 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 obviously reduces the execution efficiency of the program, so you often put an instantiation of that class in a static{} , you only need to execute the first call and improve the execution efficiency of the program as follows:

Static {     try  {   configuration.configure (configfile);    = configuration.buildsessionfactory ();      Catch (Exception e) {        System.err.println ("%%%% Error Creating sessionfactory%%%%");        E.printstacktrace ();    }}

V. Appendices

class Loading: The role of a Java command is to start a virtual machine, and the process of storing the contents of a bytecode file (. class file) into a virtual machine from a virtual machine through an input stream is a class load.

Class Loading features:
* A class is only loaded once during the lifetime of the virtual machine.
* class Loading principle: Lazy loading, can be loaded less load, because the virtual machine space is limited.
* class Loading time:
1) Create the object for the first time to load the class.
2) When a static method is called to load a class, the class is loaded when the static property is accessed.
3) The parent class must be loaded first when the subclass is loaded.
4) Creating an object reference does not load the class.
5) When a subclass calls a static method of a parent class
(1) When a subclass does not overwrite a static method of the parent class, only the parent class is loaded and the subclass is not loaded
(2) When a subclass has a static method that overrides the parent class, both the parent class and the child class are loaded
6) Access static constants, if the compiler can calculate the value of the constant, the class will not be loaded, for example: public static final int a = 123; otherwise, the class will be loaded, for example: public static final int a = Math. Pi.

static{} clause block in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.