Home

How to Use Static Initializers in Java

|
|  Updated:  
2016-03-26 12:45:27
|   From The Book:  
No items found.
Java Essentials For Dummies
Explore Book
Buy On Amazon

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
{
 <i>statements...</i>
}

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.

About This Article

This article is from the book: 

No items found.

About the book author:

Doug Lowe is the information technology director at Blair, Church & Flynn Consulting Engineers, a civil engineering firm. He has written more than 50 For Dummies books on topics ranging from Java to electronics to PowerPoint.