I found a lot of posts about static initialization blocks, however I am trying to get a little better idea of โโthe execution order and reason. The code below prints text in both static blocks and then prints text in the main static block.
I understand how the compiler calls it to make all the static blocks when the class is loaded, and then access the main method. But since the main method is static in itself, why not execute it in the order of other static blocks (not even sure if it is useful, just trying to understand the concept, and if there is an urgent reason for doing this this way). What if there is a static block that we want to run 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
source share