[JavaSE Column 60] Static code block, a piece of code executed during Java class loading

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the concept and syntax of static code blocks in Java, and gives sample codes. A static code block is a piece of code that a Java class executes during loading.

insert image description here


1. What is a static code block

A static code block is a piece of code executed during the Java class loading process, which is used to initialize the class .

The static code block is executed when the class is loaded for the first time, and it will only be executed once . Its syntax format is as follows.

static {
    
    
    // 静态代码块的代码逻辑
}

The characteristics of static code blocks are as follows 5 5At 5 o'clock, please study hard.

  1. Static code blocks are executed during the class loading phase , taking precedence over other code blocks and constructors.
  2. Static code blocks are executed only once , and automatically when the class is loaded.
  3. Static code blocks can be used to initialize static variables and initialize some static resources.
  4. Static code blocks cannot directly access non-static members (instance variables, instance methods), but can access static members (static variables, static methods).
  5. Static code blocks are executed sequentially in the order in which they are defined .

Static code blocks are often used to initialize static variables, load drivers, initialize static resources, and other operations. Its main function is to perform some necessary preparations during class loading to ensure that the static members of the class have been correctly initialized before use.

insert image description here


2. Why use static code blocks

In Java, the main function of the static code block is to perform some specific initialization operations during the class loading process. Here is 4 of 4 using static code blocks4 common scenarios, please study carefully.

  1. Initialize static variables : Static blocks can be used to initialize static variables, ensuring they are properly initialized before use. This is very useful in some cases where static resources need to be prepared in advance.
  2. Loading Drivers : In Java, loading database drivers usually requires the use of static code blocks. Static code blocks can perform related driver loading operations during class loading, thus ensuring that the driver has been correctly loaded before using the database.
  3. Initialize static resources : In some cases where static resources need to be prepared in advance, static code blocks can be used to perform some initialization operations. For example, for a web server program, the configuration information of the server can be initialized in the static code block.
  4. Execute one-time operations : Static code blocks are only executed once when the class is loaded, so they can be used to perform some operations that only need to be executed once. For example, read configuration files, establish database connections, etc.

In short, the static code block provides a mechanism for performing initialization operations during class loading, which can be used to ensure that related resources and variables have been correctly initialized when using the class. It is very useful in some specific scenarios and can improve the reliability and maintainability of the code.

insert image description here


3. How to use static code blocks

The following is a Java sample code that uses a static code block, please copy it to the local environment and try to execute it.

public class StaticBlockExample {
    
    
    private static int count;
    private static String message;

    // 静态代码块
    static {
    
    
        count = 10;
        message = "Hello, World!";
        System.out.println("静态代码块被执行");
    }

    public static void main(String[] args) {
    
    
        System.out.println("count: " + count);
        System.out.println("message: " + message);
    }
}

In the above code, we defined a StaticBlockExampleclass named which contains a static code block and a mainmethod. The static code block is executed when the class is loaded, and is used to initialize the static variables.

In the static code block, we countinitialize to 10 1010 ,messageinitialized toHello, World!.

In mainthe method, we print out the values ​​of these two static variables.

When we run this code, it will output the following result.

静态代码块被执行
count: 10
message: Hello, World!

It can be seen that when the class is loaded, the static code block is executed, and the static variables are correctly initialized, so that we can use these initialized static variables in other methods.

insert image description here


4. Static code block interview questions

1. What is the difference between a static code block and a normal code block?

Answer: The static code block is executed when the class is loaded, while the normal code block is executed when the object is instantiated. Static code blocks are executed only once, while normal code blocks are executed every time an object is instantiated.

2. What is the difference between a static code block and a constructor?

Answer: The static code block is executed when the class is loaded, and is used to initialize static member variables. The construction method is executed when the object is instantiated and is used to initialize instance member variables.

3. What is the function of the static code block?

Answer: The static code block is mainly used to perform some necessary preparations during class loading, such as initializing static variables, loading drivers, and so on. It ensures that the static members of the class have been properly initialized before use.

4. Can static code blocks access non-static members?

Answer: Static code blocks cannot directly access non-static members (instance variables, instance methods), because it is executed when the class is loaded, and non-static members belong to the object instance. But static code blocks can indirectly access non-static members by creating object instances.

5. What is the execution order of static code blocks?

Answer: When a class is loaded, static code blocks will be executed sequentially in the order in which they are defined. If there are multiple static code blocks, their execution order is consistent with the defined order.


V. Summary

This article explains the concept and syntax of static code blocks in Java, and gives sample codes. In the next blog, I will explain the knowledge points of Java object-oriented encapsulation.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132003302