Detailed description of the use of the static {} Statement block in java

Source: Internet
Author: User
Tags constant instance method


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

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 ("The Static method is executed ");
    } 
Public void display_1 (){
System. out. println ("instance method executed ");
    } 

Public class StaticBlockTest {
Public static void main (String args []) {
Try {
Class. forName ("Test ");
Class. forName ("Test ");
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
        } 
           
    }    

Result: 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 a class contains multiple static {}, it is executed in the previous and subsequent order according to the definition order of 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 outputs 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 ();

}

}

Added:


Static indicates the meaning of "global" or "static". It is used to modify member variables and member methods. It can also form static code blocks, but Java does not have the concept of global variables.

The static modified member variables and member methods are independent of any object in the class. That is to say, it is shared by all instances of the class and does not depend on a specific instance of the class.

As long as the class is loaded, the Java virtual machine can locate the class names in the method area of the runtime data zone. Therefore, a static object can be accessed before any of its objects are created without referencing any objects.

Static Member variables and member methods modified with public are essentially global variables and global methods. When the object city of the declared class does not generate a copy of static variables, instead, all instances of the class share the same static variable.

The static variable can be modified in private, indicating that the variable can be in the static code block of the class, or other static member methods of the class (you can also use -- nonsense in non-static member methods), but it cannot be directly referenced by the class name in other classes, this is important. In fact, you need to understand that private is the access permission limitation, and static means that it can be used without instantiation, so that it is much easier to understand. The effect of adding other access key words before static is also similar.

Static modified member variables and member methods are usually called static variables and static methods. They can be accessed directly by class names. The access syntax is as follows:
Class name. Static method name (parameter list ...)
Class name. Static variable name

A static code block is a static code block. When a Java virtual machine (JVM) loads a class, the code block is executed (very useful ).

1. static variables
Class member variables can be classified by static or not. One is static modified variables, such as static variables or class variables; the other is a variable that is not modified by static, called an instance variable.

The difference between the two is:
For static variables that only have one copy (memory saving) in the memory, JVM only allocates the memory for the static one time, and completes the memory allocation of the static variables during the loading process, you can directly access the available class name (convenient). Of course, you can also access it through an object (but this is not recommended ).
If an instance variable is not created, the instance variable will be allocated with memory once. The instance variables can be copied multiple times in the memory without affecting each other (flexible ).

Therefore, static variables are generally used to implement the following functions:
When a shard shares a value between objects
When the ingress facilitates variable access

2. Static method
Static methods can be called directly by class names, and can be called by any instance,
Therefore, the keyword "this" and "super" cannot be used in static methods, and the instance variables and instance methods of the class cannot be directly accessed (that is, the static member variables and member methods are not included ), only static member variables and member methods of the class can be accessed.
Because instance members are associated with specific objects! You need to understand the truth, not the memory !!!
Because the static method is independent of any instance, the static method must be implemented rather than abstract.

For example, to facilitate method calling, all the methods in the Math class in Java API are static, while the static method in the general class is also convenient for other classes to call this method.

Static methods are a special class of internal methods. They are declared as static only when needed. Internal methods of a class are generally non-static.

3. static code block

A static code block is also called a static code block. It is a static statement block independent of class members in a class. It can have multiple static code blocks and can be placed anywhere. It is not in any method body, when a JVM loads a class, it executes these static code blocks. If there are multiple static code blocks, the JVM executes them in sequence according to the sequence they appear in the class, and each code block is executed only once. For example:

Public class Test5 {
Private static int;
Private int B;

Static {
Test5.a = 3;
System. out. println ();
Test5 t = new Test5 ();
T. f ();
T. B = 1000;
System. out. println (t. B );
}
Static {
Test5.a = 4;
System. out. println ();
}
Public static void main (String [] args ){
// TODO automatically generates method stubs
}
Static {
Test5.a = 5;
System. out. println ();
}
Public void f (){
System. out. println ("hhahhahah ");
}

Running result:
3
Hhahhahah
1000
4
5

Static code blocks can be used to assign values to some static variables. In the end, these examples all use a static main method, so that the JVM can directly call the main method without creating an instance.

4. What does static and final use to represent?
Static final is used to modify member variables and member methods. It can be simply understood as a "global constant "!
For a variable, it means that once the value is given, it cannot be modified and can be accessed through the class name.
For methods, it means they cannot be overwritten and can be accessed directly by class names.

Sometimes you want to define a class member so that its use is completely independent of any object of the class. Generally, a class member must be accessed through its class object, but can create such a member, which can be used by itself without referencing a specific instance. Add the keyword static before the declaration of the member to create such a member. If a member is declared as static, it can be accessed before any object of its class is created without referencing any object. You can declare both methods and variables as static. The most common example of static members is main (). Because the main () must be called when the program starts execution, it is declared as static.

Variables declared as static are actually global variables. When declaring an object, it does not produce a copy of the static variable, but all instance variables of this class share the same static variable. Methods declared as static have the following restrictions:

They can only call other static methods.

They can only access static data.

They cannot reference this or super in any way (the keyword super is related to inheritance, as described in the next chapter ).
If you need to initialize your static variable through calculation, you can declare a static block, which is only executed once when the class is loaded. The following example shows that the class has a static method, some static variables, and a static initialization block:
// Demonstrate static variables, methods, and blocks.

Class UseStatic {
Static int a = 3;
Static int B;

Static void meth (int x ){
System. out. println ("x =" + x );
System. out. println ("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
Outside the class that defines them, static methods and variables can be used independently of any object. In this way, you only need to add the number operator after the class name. For example, if you want to call a static method from outside the class, you can use the following common format:

Classname. method ()

Here, classname is the class name and defines the static method in this class. As you can see, this format is similar to that used to call non-static methods through object reference variables. A static variable can access the -- class name plus vertex operator in the same format. This is a control version of how Java implements global functions and global variables.

The following is an example. In main (), the static methods callme () and static variables B are accessed outside of their classes.

Class StaticDemo {
Static int a = 42;
Static int B = 99;
Static void callme (){

System. out. println ("a =" + );
}
}

Class StaticByName {

Public static void main (String args []) {
StaticDemo. callme ();
System. out. println ("B =" + StaticDemo. B );
}
}

The output of the program is as follows:

A = 42
B = 99

Static members cannot be accessed by instances created by their class.

If a member without static modification is an object member, it is owned by each object.

The member with static modification is a class member, which can be directly called by a class and is shared by all objects.

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.