Static Initialization Block Tutorial

This tutorial will build on concepts from both my Instance Initialization Block Part 1 and Instance Initialization Block Part 2 tutorials. I highly recommend watching those tutorials before continuing with this tutorial.
There are some major differences between instance and static initialization blocks. A static initialization block is not dependant upon a constructor to be invoked. A static initialization block is executed when the class is first accessed, either to create an instance, or to directly access a class variable or a static method. A static Initialization block will only be executed once throughout the entire program; it won't matter how many objects you create or if you directly access a static member a bazillion times.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md StaticBlock
C:\Java>cd StaticBlock
C:\Java\StaticBlock>Notepad StaticBlock.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class StaticBlock {
    public static void main(String args[]) {
        for (int i = 0; i < 5; i ++ ) {
            new Duck(); // instance initialization block
        }

        for (int i = 0; i < 5; i ++ ) {
            Goose.myInt++; // static initialization block
            //Goose.myMethod(); // static initialization block
            //new Goose();
        }

    }
}

class Duck {
	{ System.out.println("Duck"); }
}

class Goose {
    static int myInt = 0;
    
    static { System.out.println("Goose"); } // only invoked once

    static void myMethod() { myInt++; }
}


Now switch back to the command prompt (CMD) and type in javac StaticBlock.java and press Enter.
Now type in java StaticBlock and press Enter.


C:\Java\StaticBlock>javac StaticBlock.java
C:\Java\StaticBlock>java StaticBlock
Duck
Duck
Duck
Duck
Duck
Goose


Final thoughts

The primary difference between a static initialization block and an instance initialization block is the static block runs only once throughout the entire program. The instance initialization block runs every time a new instance is created.


Tutorials