1

Does static block of class execute before the main method of same class?

Example:

public class Example {

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

    public static void main(String[] args) {

        System.out.println("bye");

    }
}

The output of this program is :

hi

bye

My doubt is why the output was not:

bye

the
  • 21,007
  • 11
  • 68
  • 101
Naz
  • 390
  • 1
  • 4
  • 15

3 Answers3

2

Ok, I got the answer when i run the program using -- java example -- in command prompt. In background java command executes main thread as -- example.main() -- which is similar to static method calling. So statements in the static block executes first than my main method.

Naz
  • 390
  • 1
  • 4
  • 15
1

Java will run the static intializers of a class before any method is called (or any instance is created). The JLS, Section 12.4.1, states:

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.

  • A static method declared by T is invoked.

  • A static field declared by T is assigned.

  • A static field declared by T is used and the field is not a constant variable (§4.12.4).

  • T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

Part of the initialization order is:

  1. 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.

Therefore, the static initializer is run first, and "hi" is printed; then main is called to print "bye".

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

It only makes sense that things in the static block are executed before anything in main(). If you were to define "static PI = 3.14157;" wont you like it to be known in the main method? Any other way will defeat the purpose.

As it turns out, static items are executed at the load time.

Neeraj Bhatnagar
  • 341
  • 1
  • 2
  • 6