How to assign a value to a static variable in Java?

In Java, there are two ways to assign values to a static variable.

  1. Assign values directly when declaring static variables.
public class MyClass {
    public static int myStaticVariable = 10;
}

In the above code, myStaticVariable is a static variable that is assigned a value of 10 at the same time it is declared.

  1. Assign a value in a static initialization block.
public class MyClass {
    public static int myStaticVariable;
    
    static {
        myStaticVariable = 10;
    }
}

In the above code, myStaticVariable is a static variable and is assigned a value in the static initialization block.

Static variables are assigned a value only once, when the class is loaded, regardless of the method used for assignment.

bannerAds