6

I found a lot of posts on static initialization blocks, however I'm trying to get a little better picture about the execution order and the reason for it. The code below prints out the text in both the static blocks and "then" prints out the text in the main static block.

I understand the way the compiler calls this is to do all the static blocks in order when the class is loaded and then access the main method. But since the main method itself is static, why not execute that in order of the other static blocks (Not even sure if its useful, just trying to understand a concept and if there's a pressing reason for it being done this way). What if there's static block 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
aparna
  • 333
  • 1
  • 8
  • 1
    Because, code of static block executes immediately after loading the class and before calling its main method – Mohammad Ashfaq Dec 24 '14 at 05:19
  • 5
    Don't confuse `static` **methods** with `static` **initializer blocks**. – Sotirios Delimanolis Dec 24 '14 at 05:22
  • I think that answered it for me. The main is still a static "method" while the rest are initializer blocks. They run without being called when the class is loaded. So it doesn't matter where these blocks are present (before or after the main - they always run first as soon as the class is loaded) – aparna Dec 24 '14 at 05:30
  • @aparna - Right. But keep in mind that the *static initializers* are executed in order i.e, as and how they appear. – TheLostMind Dec 24 '14 at 05:41
  • 1
    "What if there's a static block we want to run after the main block?" That would be a finalizer block, not an initializer block. You could add a shutdown hook (see http://stackoverflow.com/questions/5747803/running-code-on-program-exit-in-java), or put a `try`...`finally` statement in the main method. – ajb Dec 24 '14 at 05:49
  • @ajb - thanks for answering my other question about things that run after main! – aparna Dec 24 '14 at 05:52

3 Answers3

8

Static initializers are executed as soon as the class is loaded. The main method is called after the class has been loaded.

This section of the JLS discusses the sequence of events (12.1.3-4):

12.1.3. Initialize Test: Execute Initializers

In our continuing example, the Java Virtual Machine is still trying to execute the method main of class Test. This is permitted only if the class has been initialized (§12.4.1).

Initialization consists of execution of any class variable initializers and static initializers of the class Test, in textual order. But before Test can be initialized, its direct superclass must be initialized, as well as the direct superclass of its direct superclass, and so on, recursively. In the simplest case, Test has Object as its implicit direct superclass; if class Object has not yet been initialized, then it must be initialized before Test is initialized. Class Object has no superclass, so the recursion terminates here.


12.1.4. Invoke Test.main

Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.

August
  • 12,410
  • 3
  • 35
  • 51
6

The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And dont forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes. Here are a couple of points I like to mention:

If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.
If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.

After that the main method will execute. Thanks

bhadram
  • 714
  • 2
  • 8
  • 22
2

Static initializers are executed as soon as the class is initialized (a class can be loaded and initialized at a later point of time. check Class.forName()). The main() method is called after the static initializers are executed. So the output is like that.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104