How to Use Static Initializers in Java - dummies

How to Use Static Initializers in Java

By Doug Lowe

In Java, you can use initializer blocks to initialize instance variables. Initializer blocks aren’t executed until an instance of a class is created, so you can’t count on them to initialize static fields. After all, you might access a static field before you create an instance of a class.

Java provides a feature called a static initializer that’s designed specifically to let you initialize static fields. The general form of a static initializer looks like this:

static
{
 statements...
}

As you can see, a static initializer is similar to an initializer block but begins with the word static. As with an initializer block, you code static initializers in the class body but outside any other block, such as the body of a method or constructor.

The first time you access a static member such as a static field or a static method, any static initializers in the class are executed — provided that you haven’t already created an instance of the class. That’s because the static initializers are also executed the first time you create an instance. In that case, the static initializers are executed before the constructor is executed.

If a class has more than one static initializer, the initializers are executed in the order in which they appear in the program.

Here’s an example of a class that contains a static initializer:

class StaticInit
{
 public static int x;
 static
 {
  x = 32;
 }
// other class members such as constructors and
// methods go here...
}

This example is pretty trivial. In fact, you can achieve the same effect just by assigning the value 32 to the variable when it is declared. If, however, you had to perform a complicated calculation to determine the value of x — or if its value comes from a database — a static initializer could be very useful.