Java : Instance Initializer block in Java (init block)

/*init block is always executed before any constructor
//if you are not doing constructor chaining then the complete code of init block is
inserted as a first line in every constructor of class*/
//if you have done constructor chaining the complete code of init block is inserted as a first line in
//that constructor which you are not using this () as a first line
//if you want to perform some common task in every constructor of class then put the code of
that task into the init block



class InitBlock {
    int x;
    // init block
    {
        System.out.println(" first init block");
        x = 10;
    }

    // constructor
    InitBlock() {
        System.out.println("default");
        System.out.println(x);
    }

    // constructor
    InitBlock(int x) {
        System.out.println(x);
    }

    // init block
    {
        System.out.println(" secound init block");
    }

    public static void main(String... s) {
        new InitBlock();
        new InitBlock(20);
        new InitBlock();

    }
}

Output :

 first init block
secound init block
 default  10
first init block secound init block
20 first init block secound init block
default 10

Comments