Java - (Static|Dynamic) Initialization blocks

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)

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;

        myVariable = 1;

        System.out.println("Dynamic block");

    public static void main(String[] args) {
        InitiablizationBlock t = new InitiablizationBlock ();
        InitiablizationBlock t2 = new InitiablizationBlock ();


Dynamic block
Dynamic block

5 - Documentation / Reference

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap