Search code examples
javavariablesstaticstatic-variablesstatic-block

Why can you Initialize a static variable before declaring it


This code below will print out 5.

  static {
    x = 5;
  }
  static final int x;
  public static void main(String[] args) {
    System.out.println(x);

  }

I don't understand how this is legal though. There are some other links, with no clear answer to why this works

Which will be loaded first static variable or static block?

Which will be loaded first static block or static variable?

because the answer I came across people saying were something in the lines of "static blocks are initialized in the order they appear in the source code."

But in this case, x = 5 comes before static final int x in the source code


Solution

  • The primary issue involved here is the difference between compiling your code and running it. The compiler ensures that all variables have been declared. Possibly it makes two passes over the abstract syntax tree, first to find all declarations, second to check all uses have a declaration.

    Now when the code runs, variable declarations no longer matter because that was taken care of at compile time. The generated byte code performs the operations as defined in the Java source code.