1. Let’s get started!

Today, we’ll look at static variable initialization in communication. The Java virtual machine also follows this process during class loading.

2. Initialization process

At a high level, the JVM performs the following steps:

First, load and link the class. The “initialization” phase of the process then handles static variable initialization. Finally, the main method associated with the class is called. In the following discussion, we’ll explore class variable initialization.

3. The class variables

In Java, static variables are also called class variables. That is, they belong to a class, not a specific instance. Therefore, static variables are also initialized when a class is initialized. Conversely, instance variables (non-static variables) are initialized when an instance of a class is initialized. All instances of a class share static variables of that class. Take the StaticVariableDemo class as an example:

public class StaticVariableDemo {  
    public static int i;
    public static int j = 20;
 
    public StaticVariableDemo(a) {}}Copy the code

First, the JVM creates a Class object for the class StaticVariableDemo. Next, the static field initializers assign a meaningful default value to the static fields. In our example above, the class variable i is first initialized with an int default value of zero*.*

First, the JVM creates a Class object for the StaticVariableDemo Class. Next, static fields will be given a meaningful default value. In the example above, the class variable I is first initialized with the default value 0 of int. The order in which the code is written applies to the order in which static fields are initialized. First, I will be initialized, and then j will be initialized. After initializing *, the * class and its static members will be visible to other classes.

4. Variables in static blocks

Here’s another example:

public class StaticVariableDemo {  
    public static int z;
 
    static {
        z = 30;
    }
    public StaticVariableDemo(a) {}}Copy the code

In this case, the variables are initialized sequentially. First, the JVM initially assigns the default int value 0 to the variable Z. Then, in the static block, it is changed to 30.

5. Statically nested variables in a class

Finally, let’s take the nested classes in the external StaticVariableDemo class as an example:

public class StaticVariableDemo {  
    public StaticVariableDemo(a) {}
    
    static class Nested {
        public static String nestedClassStaticVariable = "test"; }}Copy the code

In this example, the StaticVariableDemo class loads the Nested class. It will nestedClassStaticVariable to initialize static variables.

6. The final

In this short article, we briefly explained static variable initialization. For more information, see the Java language specification.