Instance Initialization Block Part 1 Tutorial

Up until this point, I have discussed two ways that we can execute statements in a class: constructors and methods. This tutorial will introduce you to a third way – the initialization block. There are two types of initialization blocks, an instance initialization block and a static initialization block. This tutorial will discuss only the instance initialization block, I will be discussing the static initialization block after the part 2 tutorial. An instance initialization block is simply a pair of opening and closing braces inside of a class, but not inside of a method or constructor. Statements inside of the block are executed as an instance of the class is created. The structure for a code block looks like this:
(class) (ClassName) {
     { statements ... }
}
Instance initialization blocks are quite useful when you need to perform some complex logic when the object is created, but you don't want to put the code into a constructor. A very common reason to use an initialization block would be in a case where you have multiple overloaded constructors and you don't want to duplicate the same code over and over again.



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 InstanceBlockOne
C:\Java>cd InstanceBlockOne
C:\Java\InstanceBlockOne>Notepad InstanceBlockOne.java

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


import java.time.*; // jdk 1.8 and above ... type "javac - version" at CMD to find out
import java.time.format.*;
class InstanceBlockOne {
    public static void main(String args[]) {
        if (args.length == 0) {    
            new Welcome();
        } else {
            new Welcome(args[0]);
        }
    }
}

class Welcome {
    Welcome() {
        super();
    }

    Welcome(String name) {
        super();
        System.out.println("Welcome back " + name);
    }

    // instance initialization block
    {
        System.out.println();

        int hour = LocalDateTime.now().getHour();
        if (hour <= 11) {
            System.out.println("Good Morning!");
        } else if (hour >= 12 && hour < 18) {
            System.out.println("Good Afternoon!");
        } else if (hour >= 18 && hour < 21) {
            System.out.println("Good Evening!");
        } else  {
            System.out.println("Good Night!");
        }

        // don't worry the syntax on the next line - just know that it returns the current date.
        System.out.println("Today is: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("eeee, MMMM dd, yyyy")));
    }

    // Methods ...
    
}

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


C:\Java\InstanceBlockOne>javac InstanceBlockOne.java
C:\Java\InstanceBlockOne>java InstanceBlockOne // try it without an argument and with an argument
results will vary


Final thoughts

In this tutorial I presented an example of how you can save time and optimize your code by using an instance initialization block. In part 2 of this tutorial I will explain in detail how they actually work.


Tutorials