12 Aug

Java: Static initialization Blocks

In this post I want to give an overview about what Static initialization Blocks in Java are and why they are useful.

What are static initalization blocks?

Static inializer is a code block enclosed with a pair of braces and preceded by a ‘static’ keyword. A class can contain one or more static initializer blocks. These blocks can be anywhere in the class definition where we can have a field or a method. The Java runtime guarantees that all the static initialization blocks are called in the order in which they appear in the source code. The syntax is as follows:

static { 
    //CODE
 }

The code in the static initializer block will be executed by the virtual machine when the class is loaded.

Just for completion it shall be mentioned that there is another initialization block, the instance initialization block, which will be executed when an instance of the class will be initialized.

Consider the following example:

class Employee {
   static {
      System.out.println("Static initialization block");
   }

   {
      System.out.println("Instance initialization block");
   }

   public Employee() {
      System.out.println("Constructor");
   }

   public static void main(String[] args) {
       Employee e = new Employee();
   }
}

This example shall illustrate the execution order. First the static initalization block is executed, followed by the instance intialization block and finally the constructor block.

Why do we need static initalization blocks?

The static initializer block will be called on loading of the class, and will have no access to instance variables or methods. It is often used to create static variables.

The non-static initializer block on the other hand is created on object construction only, will have access to instance variables and methods, and will be called at the beginning of the constructor, after the super constructor has been called (either explicitly or implicitly) and before any other subsequent constructor code is called. I’ve seen it used when a class has multiple constructors and needs the same initialization code called for all constructors. Just as with constructors, you should avoid calling non-final methods in this block.

The easiest way of initializing fields (static or instance) in Java at the time of their declaration is simply by providing a compile time constant value of a compatible data type. For example:

public class InitializationWithConstants{

public static int staticIntField = 100;
private boolean instanceBoolField = true;

}

This type of initialization has its limitation due to its simplicity and it can not support initialization based even on some moderately complex logic – like initializing only selected elements of a complex array using some logic in a for loop. So, the main reason why to use static initialization blocks is when you have complex initializations which can not be expressed in a single expression.

Here comes the need for static initialization blocks and initializer blocks for initializing static and instance fields, respectively.

Other examples on which static initialization blocks can be used:

  • Loading drivers and other items into the namespace. (For example ‘Class.forName(“com.mysql.jdbc.Driver”)’)
  • Initialize your complex static members once (possibly for singletons/etc)
  • Logging
  • Creating/parsing prepared SQL statements

Alternative to Static Initialization Blocks

A private static method is a suitable alternative to the static initialization blocks. In fact it has some advantages over static initialization blocks as well like you can re-use a private static method to re-initialize a static field in case you need it. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a ‘public’ static method can’t do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method ‘public’. An example:

public class InitializationWithPrivateStaticMethod{

   public static int staticIntField = privStatMeth();
   private boolean instanceBoolField = true;

   private static int privStatMeth() {
       //compute the value of an int variable 'x'
       return x;
   }
}

Resources

http://openbook.galileocomputing.de/javainsel9/javainsel_05_006.htm#mj2781d1c908a54becfd6d5996eac112b7

http://java.silke-wingens.de/2010/04/19/initialisierungsblocke/

http://careerride.com/Java-Static-Initializers.aspx

http://www.engfers.com/code/static-initializer-block/

http://geekexplains.blogspot.de/2009/06/static-initialization-blocks-their.html

http://ag-kastens.uni-paderborn.de/lehre/material/java_vorlesung/folien/java_node3.html

Leave a Reply

Your email address will not be published. Required fields are marked *


five + 2 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" extra="">