Detailed description of static {} statement Blocks

Source: Internet
Author: User

Disclaimer: reprinted, please indicate the source

Static {} (static block) is executed only once when the class is loaded. It is generally used to initialize static variables and call static methods, next we will discuss in detail the features and applications of this statement block.

 

1. During a program execution, the content in the static {} statement block is only executed once. See the following example:

Example 1

 

[Java]View plaincopy
  1. Class test {
  2. Public static int x = 100;
  3. Public final static int y; = 200
  4. Public test (){
  5. System. Out. println ("test constructor execution ");
  6. }
  7. Static {
  8. System. Out. println ("static statement block execution ");
  9. }
  10. Public static void display (){
  11. System. Out. println ("the static method is executed ");
  12. }
  13. Public void display_1 (){
  14. System. Out. println ("instance method executed ");
  15. }
  16. }
  17. Public class staticblocktest {
  18. Public static void main (string ARGs []) {
  19. Try {
  20. Class. forname ("test ");
  21. Class. forname ("test ");
  22. } Catch (classnotfoundexception e ){
  23. E. printstacktrace ();
  24. }
  25. }
  26. }

 

Result: You will find that although two classes are executed. forname ("test") statement, but only one "static method executed" statement is output; in fact, the second class. the forname () Statement is invalid because one class is loaded only once in the life cycle of the VM, And because static {} is executed along with the class loading, no matter how many new object instances you have, static {} is executed only once. --For more information about class loading, see the appendix in this article.

 

Ii. Timing of executing the static {} statement block (in fact, it is the time for class loading in the Appendix)

 

As mentioned above, static {} is executed when the class is loaded. We must accurately understand the meaning of class loading. The meaning is as follows:

1. When class. forname () is used to display the loading, the example 1 above is shown;

2. when instantiating a class, for example, changing the content of the main () function to: test T = new test (); // the principle is the same as that of 1, are displayed to load 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 static methods of the class, for example, changing the content of the main () function to: Test. Display ();

4. When calling static variables of the class, for example, changing the content of the main () function to: system. Out. println (test. X );

 

In general, there are four situations, but we need to pay special attention to two points:

1. When calling static constants of a class, the class will not be loaded, that is, the static {} statement block will not be executed. You can verify it yourself (Set main () change the function content to system. out. println (test. y);), you will find that the program outputs only one 200; (this is the specification of the Java Virtual Machine. If the compiler can calculate the value of a constant for a static constant of the runtime class, the class will not be loaded; otherwise, the class will be loaded)

2. Use class. in the forname () format, we can also set whether to load the class, for example, set the class. change 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, and static {} is not executed.

 

Iii. execution sequence of the static {} statement Block

 

 

1,When there are multiple static {} in a class, it is executed in the previous and subsequent order defined by static;

2,The call statement is executed only after the content of the static {} block is executed;

Example 2

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 a static variable is assigned an initial value (for example, static int x = 100) during definition, the value assignment operation is also completed during class loading, in addition, when a class contains both static {} and static variables, the principle of "first defining first execution" is also followed;

Example 3

Class test {
Public static int x = 300;
Static {
System. Out. println (X );
X = 200;
System. Out. println (X );
}
}

Public class staticblocktest {
Public static void main (string ARGs []) {
System. Out. println (test. X );
}
}

Result: The program will output 300,200,200 in sequence, and then execute the static {} statement block after running X = 300.

 

Iv. Static {} statement block Application

 

1. Applications in JDBC

Readers familiar with JDBC should know that Java has a drivermanager class for managing various database drivers and establishing new database connections. The drivermanager class contains some drivers classes. These drivers classes must register themselves by calling the drivermanager's registerdriver () method. When will the registration happen? The answer is as follows:

All drivers classes must contain a static method. Using this static method, you can create an instance of this class and register it with the drivermanage class when loading the instance. We often use class. forname () is used to load the driver. registration occurs during the execution of this statement. The static method of drivers mentioned earlier is put in static, when the driver is loaded, the static {} will be executed to complete the registration.

 

2. Applications in hibernate

Sessionfactory in Hibernate is a heavyweight class. Creating an object instance of this class consumes a lot of system resources. If you create an instance of this class every time you need it, it will obviously reduce the program execution efficiency, therefore, we often put the class instantiation in a static {}, which only needs to be executed during the first call to improve the execution efficiency of the program, as shown below:

Static {
Try {
Configuration. Configure (configfile );
Sessionfactory = configuration. buildsessionfactory ();
} Catch (exception e ){
System. Err. println ("% error creating sessionfactory % ");
E. printstacktrace ();
}
}

 

V. Appendix

 

Class loading:The role of Java commands is to start the virtual machine. The virtual machine reads the content in the bytecode file (. Class file) from the disk into the virtual machine through the input stream, and stores the content in the Process of class loading.

 

Class loading features:
*In the life cycle of a VM, a class is loaded only once.
*Class loading principle: delayed loading means less loading because the space of virtual machines is limited.
*Class loading time:
1) class to be loaded when an object is created for the first time.
2) classes must be loaded when static methods are called, and classes will be loaded when static properties are accessed.
3) When a subclass is loaded, the parent class must be loaded first.
4) Creating object references does not load classes.
5) when the subclass calls the static method of the parent class
(1) When the subclass does not cover the static method of the parent class, only the parent class is loaded, not the subclass.
(2) When a subclass has a static method that overwrites the parent class, it loads both the parent class and the Child class.
6) Access static constants. If the compiler can calculate the value of a constant, classes will not be loaded, for example, public static final int A = 123; otherwise, classes will be loaded, for example: public static final int A = math. pi.

 

Original article: http://blog.csdn.net/lubiaopan/article/details/4802430

Detailed description of static {} statement Blocks

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.