105

Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in the order they appear in the code. I've read that it's the same across classes, but some sample code I wrote disagrees with that. I used this code:

package pkg;

public class LoadTest {
    public static void main(String[] args) {
        System.out.println("START");
        new Child();
        System.out.println("END");
    }
}

class Parent extends Grandparent {
    // Instance init block
    {
        System.out.println("instance - parent");
    }

    // Constructor
    public Parent() {
        System.out.println("constructor - parent");
    }

    // Static init block
    static {
        System.out.println("static - parent");
    }
}

class Grandparent {
    // Static init block
    static {
        System.out.println("static - grandparent");
    }

    // Instance init block
    {
        System.out.println("instance - grandparent");
    }

    // Constructor
    public Grandparent() {
        System.out.println("constructor - grandparent");
    }
}

class Child extends Parent {
    // Constructor
    public Child() {
        System.out.println("constructor - child");
    }

    // Static init block
    static {
        System.out.println("static - child");
    }

    // Instance init block
    {
        System.out.println("instance - child");
    }
}

and got this output:

START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END

The obvious answer from that is that parents' blocks run before their children's, but that could just be a coincidence and doesn't help if two classes aren't in the same hierarchy.

EDIT:

I modified my example code by appending this to LoadTest.java:

class IAmAClassThatIsNeverUsed {
    // Constructor
    public IAmAClassThatIsNeverUsed() {
        System.out.println("constructor - IAACTINU");
    }

    // Instance init block
    {
        System.out.println("instance - IAACTINU");
    }

    // Static init block
    static {
        System.out.println("static - IAACTINU");
    }
}

As implied by the class name, I never referenced the new class anywhere. The new program produced the same output as the old one.

slim
  • 40,215
  • 13
  • 94
  • 127
Pops
  • 30,199
  • 37
  • 136
  • 151
  • 1
    See there (super concise & clear) : http://blog.sanaulla.info/2008/06/30/initialization-blocks-in-java/ – Benj Mar 05 '13 at 10:58
  • 1
    A big revelation here is that parent constructor will execute before child instance initializer ! – ACV Jan 08 '19 at 12:58

8 Answers8

99

See section 12.4 and 12.5 of the JLS version 8, they go into gory detail about all of this (12.4 for static and 12.5 for instance variables).

For static initialization (section 12.4):

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.
  • T is a class and 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.

(and several weasel-word clauses)

Roland
  • 7,525
  • 13
  • 61
  • 124
Keith Randall
  • 22,985
  • 2
  • 35
  • 54
  • 2
    Best possible answer. Great job! – Chip Uni Jan 05 '10 at 17:08
  • Good answer. I scanned the page and it contains the fundamentals for object oriented design as it relates to java. So it is a must read for every java developer. – Peter Schuetze Jan 05 '10 at 17:16
  • Good one . Straight from the creators – human.js Jun 20 '12 at 04:26
  • 1
    This answer covers everything. It should be the accepted answer. – Timmos Nov 20 '13 at 11:29
  • I believe this part of the JLS to be unprecise (and if you want even slightly incorrect). The 4th item should be: "A static field declared by T is used and the field is not a constant variable with a literal value initializer." As example see: http://pastebin.com/1XfczpjR, `C.main` prints `42` but according to the rules above `B` should never have been initialized, as `answer` is a constant variable (compare to JSL 4.12.4). – Steffen Heil May 27 '15 at 09:14
  • @SteffenHeil: From the JLS: "A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable." So the variable *answer* is not a constant variable because it is not assigned a compile-time constant value. – Keith Randall May 27 '15 at 15:10
  • @Keith, 15.28 defines "compile-time constant expression", not "constant variable". But I think we all know what was meant... – Steffen Heil May 28 '15 at 15:50
  • @SteffenHeil: Sorry, that quote was from 4.12.4. 15.28 is what is referenced by that quote. – Keith Randall May 28 '15 at 16:13
66

The static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field.

So, for multiple classes, this totally depends on the code that's run to cause those classes to get loaded.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • A class can get loaded during a dependent's resolve cycle. Simply having a declaration of a variable of a given class will require the loading of that class. – alphazero Jan 05 '10 at 17:07
  • That seems contrary to what section 12.4 (see Keith's excellent answer) says. – C. K. Young Jan 05 '10 at 17:12
  • 1
    I agree. The variable declaration will (I think) not do it, unless it's a static variable with initialization. – Carl Smotricz Jan 05 '10 at 17:17
  • Right, and if you're not initialising with null, then you have to call a constructor or factory method, both of which call cause the class to get loaded. – C. K. Young Jan 05 '10 at 17:27
  • "Resolution is the process of checking symbolic references from Test to other classes and interfaces, by loading the other classes and interfaces that are mentioned and checking that the references are correct" seems to indicate its JVM implementation specific. – alphazero Jan 05 '10 at 18:03
  • Accessing a static field does not yield class initialization when that field is a constant by being declared `final`. Also note that, while not being a field, accessing `SomeClass.class` does not make `SomeClass` initialize either. – Timmos Nov 20 '13 at 11:28
  • +1 for *"The class is first loaded when you first access it"*. – sfinja Nov 30 '13 at 21:40
  • 2
    Have you read the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4)? Static initialization *does not* get run when the class is loaded. – Hot Licks Aug 09 '14 at 13:45
  • @HotLicks The second sentence of my post talks about what loading a class means, which is pretty much most of the cases listed in the JLS. Yes, it's a less formal answer than an actual JLS citation, but I think it's close enough to reality and is more accessible. – C. K. Young Aug 10 '14 at 02:54
  • 1
    Except that the class is loaded when it's referenced by another class, which may be a long time before it's initialized. – Hot Licks Aug 10 '14 at 03:00
  • @HotLicks Fine, I removed all references to "loading" a class. – C. K. Young Aug 10 '14 at 03:29
  • @Timmos how much can we trust this behavior in a sense that we can really control when things will be initialized considering future java updates? I want to base my project on a granted predictable initialization order. So, I guess a static block, whenever any initialization happens, may grant that. – Aquarius Power Mar 05 '15 at 19:56
37

Keith's and Chris's answers are both great, I'm just adding some more detail for my specific question.

Static init blocks run in the order in which their classes are initialized. So, what order is that? Per JLS 12.4.1:

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.
  • T is a class and 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, and an assert statement (§14.10) lexically nested within T is executed.

Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.

To illustrate, here's a walkthrough of what's happening in the example:

  1. Enter main
  2. Print "START"
  3. Attempt to create first instance of Child, which requires initialization of Child
  4. Attempting to initialize Child causes initialization of Parent
  5. Attempting to initialize Parent causes initialization of Grandparent
  6. At the start of initialization of Grandparent, Grandparent's static initialization block is run
  7. Technically, Object gets the last say in the initialization chain by virtue of being Grandparent's parent, but it has nothing to contribute
  8. After Grandparent's static initialization block ends, program falls back to Parent's static initialization block
  9. After Parent's static initialization block ends, program falls back to Child's static initialization block
  10. At this point, Child is initialized, so its constructor may proceed
  11. Since IAmAClassThatIsNeverUsed never gets referenced, none of its code ever runs, including static initializer blocks
  12. The rest of this walkthrough doesn't concern static initializers and is included only for completeness
  13. Child's constructor implicitly calls super() (i.e., Parent's constructor)
  14. Parent's constructor implicitly calls super() (i.e., Grandparent's constructor)
  15. Grandparent's constructor does the same, which has no effect (again, Object has nothing to contribute)
  16. Immediately after Grandparent's constructor's call to super() comes Grandparent's instance initializer block
  17. The rest of Grandparent's constructor's constructor runs and the constructor terminates
  18. The program falls back to Parent's constructor, immediately after its call to super() (i.e., Grandparent's constructor) resolves
  19. As above, Parent's instance initializer does its thing and its constructor finishes up
  20. Similarly, the program returns to and completes Child's constructor
  21. At this point, the object has been instantiated
  22. Print "END"
  23. Terminate normally
Pops
  • 30,199
  • 37
  • 136
  • 151
  • 2
    in 12.4.1 we also find: `Before a class is initialized, its direct superclass must be initialized, ...` – user85421 Jan 05 '10 at 19:06
3

There is one case in which a static block will not be called.

class Super {
    public static int i=10;
}
class Sub extends Super {
    static {
        system.out.println("Static block called");
    }
}
class Test {
    public static void main (String [] args) {
        system.out.println(Sub.i);
    } 
}

The above code outputs 10


Update from an "editor"

The technical explanation for this is in JLS 12.4.1

"A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface."

The intuitive explanation is Super.i and Sub.i are actually the same variable, and nothing in Sub actually needs to be initialized for the Super.i to get the correct value.

(It would be different if the initialization expression for Super.i referred to the Sub class. But then you would have a cycle in the initialization order. A careful reading of JLS 12.4.1 and JLS 12.4.2 explains that this is allowed, and allows you to work out exactly what would happen in practice.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Java Main
  • 1,521
  • 14
  • 18
1

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

Initialization of an interface consists of executing the initializers for fields (constants) declared in the interface.

Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class are not initialized. Similarly, the superinterfaces of an interface are not initialized before the interface is initialized.

Bala
  • 4,427
  • 6
  • 26
  • 29
0

You can have multiple static and instance initializers in the same class, therefore

  • Static initializers are called in the textual order they are declared (from 12.4.2)
  • Instance initializers are called in the textual order they are declared (from 12.5)

Each is executed as if it was a single block.

Martin Tapp
  • 3,106
  • 3
  • 32
  • 39
0
class A {
  public A() { 
    // 2
  }
}

class B extends A{
  static char x = 'x'; // 0
  char y = 'y'; // 3
  public B() { 
    // 4
  }

  public static void main(String[] args) {
    new B(); // 1
  }
}

Numbers in the comment indicate the evaluation order, the smaller, the earlier.

As the example showed,

  1. static variable
  2. main
  3. constructor of superclass
  4. instance variable
  5. constructor
GraceMeng
  • 949
  • 8
  • 6
-1

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

kindly check java documentation.

then clearly mentioned no matter how may static blocks are there they will be executed as a single block in the order they appear

So,

My understanding here is java is looking your code as

static{
i=1;
i=2;
}

static int i;

that is why you are getting output 2

hope this is helpful