Java - (Static|Dynamic) Initialization blocks

> Procedural Languages > Java

1 - About

Initialization block are used to initialize field with a complex logics such as:

  • with a function that throw exceptions.
  • check if a particular class is loaded
  • only one execution with the static modifier (for a counter for instance)
Advertising

3 - Type

3.1 - Static

static {
    // whatever code is needed for initialization goes here
}

The static initialization block only gets:

  • called once, no matter how many objects of that type you create.
  • executed first (e.g. before your constructor and before any static methods) once the JVM loads your class.

A JDBC driver makes use of a static initializer block to register itself in the DriverManager

3.2 - Dynamic

{
    // whatever code is needed for initialization goes here
}

The dynamic initialization block gets called every-time a class is instantiated. They act like extensions of constructor methods.

4 - Example

public class InitiablizationBlock {
 
    static int myVariable;
 
    static{
        System.out.println("Static");
        myVariable = 1;
    }
 
    {
        System.out.println("Dynamic block");
    }
 
    public static void main(String[] args) {
        InitiablizationBlock t = new InitiablizationBlock ();
        InitiablizationBlock t2 = new InitiablizationBlock ();
    }
}

Output:

Static
Dynamic block
Dynamic block
Advertising

5 - Documentation / Reference

lang/java/initialization_block.txt · Last modified: 2017/02/12 21:06 by gerardnico