Java static blocks and related content

Source: Internet
Author: User
Tags instance method

Original address: http://blog.csdn.NET/lubiaopan/article/details/4802430 thank the original author!

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

[Java]View Plaincopy
  1. Class test{
  2. public static int x=100;
  3. public final static int y;=
  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 ("static method is executed");
  12. }
  13. public void Display_1 () {
  14. System.out.println ("instance method is 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 class.forname ("Test") statements are executed, only one "static method executed" statement is output;

In fact, 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 your object instance is new, static{} executes only once.

two , static{} statement block execution time

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, 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, 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. When calling Static constants of a class, the class is not loaded, that is, the static{} statement block is not executed, and the reader can verify for itself (change the contents of the main () function to System.out.println (TEST.Y);). You will find that the program only outputs a single, ( This is the Java virtual machine's provisions, when accessing the static constants of the class, if the compiler can calculate the value of the constant, the class will not be loaded, 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 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 to the initial value at the time of definition (such as static int x=100), then the assignment operation is done when the class is loaded, and when there are static{} and static variables in a class, the same principle of "first defining first execution" is followed;

Example Three

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 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 static{},

When the driver is loaded, the static{} is executed and the registration is completed.

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);
Sessionfactory = Configuration.buildsessionfactory ();
} catch (Exception e) {
System.err.println ("%%%% Error Creating sessionfactory%%%%");
E.printstacktrace ();
}
}

V. Appendices

The

class loads: The role of the Java command is to start the virtual machine, and the virtual machine reads the contents of the bytecode file (. class file) from the disk into the virtual machine through the input stream, and the process of saving it is class loading.

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.

Java static blocks and related content

Related Article

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.