0

What is the defined execution order between static blocks and static initialization functions? Is it their order in the class definition?

For example:

public class Test {

    static  {System.out.println("1");   }

    static int x = getX();  static int getX() { System.out.println("2"); return 5; }

    static { System.out.println("3"); }
}

Prints 1,2,3 on my system. Is this guaranteed by Java? I've seen similar questions, but not one that contained an answer for this.

Gonen I
  • 5,576
  • 1
  • 29
  • 60
  • 2
    Have a look at the [JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.2).: "Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, _in textual order_, as though they were a single block." - Note, however, that it's easy to write code that confuses the developer on the order of execution so you should be _very_ careful when relying on such things. – Thomas Jan 27 '17 at 11:53
  • `static` is 99.999% sequential. – Azodious Jan 27 '17 at 11:54

0 Answers0