Java – order of static initialization blocks
I found a lot of posts on the static initialization block, but I tried to better understand the execution order and why The following code prints the text in two static blocks, and then "then" prints the text in the main static block
I understand that the compiler calls it by executing all static blocks sequentially when the class is loaded, and then accessing the main method But since the main method itself is static, why not execute it in the order of other static blocks (not even sure whether it is useful, just trying to understand a concept and whether there is an urgent reason to do so) What if we want to run a static block after the main block?
class Cat { static { System.out.println("This block welcomes you first"); } public static void main(String[] args) { System.out.println("Meow world "); } static { System.out.println("This block welcomes you after"); } }
Actual output
This block welcomes you first This block welcomes you after Meow world
Why not?
This block welcomes you first Meow world This block welcomes you after
Solution
The static initializer is executed immediately after the class is loaded After the class is loaded, the main method is called.
This part of JLS discusses the sequence of events (12.1.3-4):