Perfect analysis: initialization process of static variables

 Perfectly resolved : static variable a is in the class loading process. This problem involves the bottom layer of the JVM.

Table of contents

1.Problem description

2.Solution process

3. Practice


1.Problem description

Please refer to the picture above for specific questions (ps: this question was asked by a netizen, so I just summarized it). Netizens asked me directly

 Haha, there are pictures and the truth

2.Solution process

Analysis: In order to understand this problem, we first need to learn how the underlying class loader of the JVM works.

Pay attention to the above process

1. The preparation phase in the link step: allocate storage space for class variables and set initial values. Then the class variable at this moment refers to the static variable a, so the initial value assigned to a is 0. 

2. Wait until the initialization step to actually assign a value to the class command, which means that the class variable a will become 5.

3. Practice

Analyze the output of the following program

public class Test4 {

    {
        a=200;
        System.out.println("==实例代码块=="+a);
    }

    static int a;

    static{
        a=100;
        System.out.println("==静态代码块=="+a);
    }


    public static void main(String[] args) {
        System.out.println(a);
        System.out.println(new Test4().a);
    }

}

The running results are as follows:

Analysis: 1. Static variables can be used directly without declaration in the instance code block.

           2. Static variables and static code blocks are executed when the class is loaded.

I record the problems I encountered at work and the process of solving them, and I hope it can help everyone!

Guess you like

Origin blog.csdn.net/white0718/article/details/132148011