What is a static block and how should I use it?

John Mitchell

Static blocks are defined by in section 8.7 of the JLS, second edition. Basically, static blocks are blocks defined within the body of a class using the static keyword but which are not inside any other blocks. I.e.,

public class shme
    static int foo = 12345;

	foo = 998877;

The primary use of static initializers blocks are to do various bits of initialization that may not be appropriate inside a constructor such that taken together the constructor and initializers put the newly created object into a state that is completely consistent for use.

In contrast to constructors, for example, static initializers aren't inherited and are only executed once when the class is loaded and initialized by the JRE. In the example above, the class variable foo will have the value 998877 once initialization is complete.

Note also that static initializers are executed in the order in which they appear textually in the source file. Also, there are a number of restrictions on what you can't do inside one of these blocks such as no use of checked exceptions, no use of the return statement or the this and super keywords.

Personally, I think this is yet another odd little wart in the Java language that is due to the fact that Java doesn't have first-class classes. Sigh.