javastaticstatic-initializationstatic-initializer

Why static initializer allow re-initialization of static variable in Java?


I am studying static initializers in Java. I came through a source code as given below:

    public class A {
       private static int count = 5;
       final static int STEP = 10;
       boolean alive;
       static {
         count = 1;
       }
       public static void main(String[] args) {
          A a = new A();
          System.out.println(A.count);
       }
    }

My question is that why the compiler is not complaining about the variable count being reassigned the value 1 in count = 1 in the static initializer block. I know that Java allows forward referencing as long as declaration-before-read rule (i.e. any identifier should not be read before declaration) is followed which is for all initializers and if not then the reference (or identifier) must come on the left-hand side of the assignment. I also know that if multiple static initializer expressions and static field initializer blocks are written in a class then their order of execution is sequential.

According to me the flow of execution should be: The class is loaded and then all the static initializer (expressions and blocks) are executed in sequence, due to which the count will be initialized to value 5 and then the default constructor will be executed calling the super() and initializing the instance variable alive to default value. But why it is not throwing an error that static variable count has been re-initialized (as it is not the case of forward reference), instead, it gives the output 1. Does that mean that we can re-initialize static variables through static initializer blocks?


Solution

  • As long as you manipulate the static variable within the class it is initialized you won't get an error from the compiler. If you had declared it as final the behavior you mentioned would have occurred. Keep in mind that static means that the variable is shared across all instances of the object, so it only gets initialized and memory allocated once.