SoFunction
Updated on 2025-04-05

Detailed explanation of static code blocks and constructed code blocks in Java

1. Static code blocks

1. The underlying principle

Static code blocks are executed when the bytecode of the class is loaded into the JVM and throughout the JVM lifecycleWill only be executed once

When the JVM loads a class, it first loads the bytecode of the class, and then looks for static members and static code blocks in the class.

All static code blocks are executed in the order they are defined in the class.

2. Execution timing

The execution time of static code blocks is during class loading. Class loading usually occurs when one of the following:

  • The first instance of the class is created.
  • Access the first static member of the class (static variable or static method).
  • Use reflection mechanism to load classes.

When any of the above conditions are met, the JVM will load the class and execute all static code blocks in the class.

3. Function

  • Initialize static variables: Complex initialization operations can be performed on static variables in static code blocks.
  • Perform one-time setup: For example, loading configuration files, initializing database connection pools, etc., only one operation is required when the class is loaded.
  • Used to capture the loading point in the class: Sometimes we want to execute some logic when the class is loading, and static code blocks are a very suitable place.

4. Example

public class StaticBlock {
    static {
        ("Static code block 1 is executed.");
    }
    
    static int staticVar = initStaticVar();

    static {
        ("Static code block 2 is executed.");
    }
    
    private static int initStaticVar() {
        ("The static variable is initialized.");
        return 1024;
    }
    
    public static void main(String[] args) {
        ("The main method is executed.");
        ("The value of the static variable staticVar is: " + staticVar);
    }
}

The running result is:

Static code block 1 is executed.
Static variables are initialized.
Static code block 2 is executed.
The main method is executed.
The value of the static variable staticVar is: 1024

In this example:

  • Static code blocks are executed in the order they are defined in the class.
  • Static variablesstaticVarThe initialization occurs between the first static code block and the second static code block.
  • These operations are only performed once the class is first loaded.

2. Construct code blocks

1. The underlying principle

The constructed code block is executed every time an object is created. In the process of constructing objects by JVM,A constructor block is executed before the constructor is called.

A constructed code block can be used to initialize instance variables when object creation, or to execute some code that needs to be executed each time an object is created.

2. Execution timing

Each time an object is created, the JVM first allocates the object's memory in the heap memory and then follows the following steps:

  • Initialize instance variables to default values.
  • Execute construct code blocks, executed in the order they are defined in the class.
  • Execute the constructor.

Therefore, the execution of the construct code block is before the construction method, and even if the assignment of instance variables is performed in the construction method, the code in the construct code block will be executed before these operations.

3. Function

  • Complex initialization of instance variables: Construct code blocks are suitable for complex initialization operations of instance variables, especially when the initialization logic needs to be shared among multiple constructors.
  • Logic executed every time an object is created: The code in the constructed code block is executed every time an object is created, so it can be used to execute some common logic when object creation.

4. Example

public class ConstructBlock {
    {
        ("Constructing code block 1 is executed.");
    }
    
    int constructVar = initConstructVar();
    
    {
        ("Constructing code block 2 is executed.");
    }
    
    private int initConstructVar() {
        ("Member variables are initialized.");
        return 1024;
    }
    
    public ConstructBlock() {
        ("The constructor is executed.");
    }
    
    public static void main(String[] args) {
        ("Create the first object:");
        new ConstructBlock();
        
        ("\nCreate a second object:");
        new ConstructBlock();
    }
}

The running result is:

Create the first object:
Construct code block 1 is executed.
Member variables are initialized.
Construct code block 2 is executed.
The constructor is executed.

Create a second object:
Construct code block 1 is executed.
Member variables are initialized.
Construct code block 2 is executed.
The constructor is executed.

In this example:

  • Each time an object is created, the initialization logic for constructing the code block and instance variables is executed.
  • No matter which constructor you call, the constructor code block will be executed, ensuring that some logic can be run before all constructors are executed.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.