init block and cunstructor problem

when we use init block , the code in init block pasted in all constructor automaticaly.

but when we use cunstructor chaning it does not hepend … why??

class InitBlock
{
{

System.out.println(“In it block”);

}

InitBlock(int x, int y)

{

this(1,2,3);

int c =x+y;

System.out.println©;}

InitBlock(int x, int y, int z)

{

int c =x+y+z;

System.out.println©;}

public static void main(String…s)

{

InitBlock b = new InitBlock(5,6);
}
}

output

init block

6

11

but i think, acording to init block working it should be

init block

6

init block

11

I’m not sure if I understand you well, but you are not correct.

Here is the code (pastebin version):

public class InitBlockTest {

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

    public InitBlockTest() {
        this( 0 );
        System.out.println( "InitBlockTest()" );
    }

    public InitBlockTest(final int n) {
        System.out.println( "InitBlockTest(n=" + n + ")" );
    }

    public static void main( final String[] args ) {
        new InitBlockTest();
        System.out.println("=== === ===");
        new InitBlockTest( 4 );
    }

}

When you run this code, the output is

in init
InitBlockTest(n=0)
InitBlockTest()
=== === ===
in init
InitBlockTest(n=4)

as you can see, the init block was called.

In fact it’s not working like “code is pasted in all constructors”, maybe that’s why you are surprised, it works like “init block is called when object in constructed”.

I found the source of your confusion, it’s writen in this tutorial, but my example above shows, that’s incorrect.

I tried to find the description in Java language specification, but I didn’t find some simple description :frowning:

class InitBlock{
{
System.out.println(“In it block”);
}
InitBlock(int x, int y)
{
this(1,2,3);
int c =x+y;
System.out.println©;}
InitBlock(int x, int y, int z)
{
int c =x+y+z;
System.out.println©;}
public static void main(String…s)
{
InitBlock b = new InitBlock(5,6);
}
}

output
init block
6
11

but i think, acording to init block working it should be
init block
6
init block
11

An init block is executed only once per object.

In a constructor :

  1. The first line should either be a call to super constructor or to some other constructor of the same class.

2)If nothing is specified an implicit call to no-arg constructor is placed as the first statement.

The init block is executed immediately after the super class constructor finishes execution.

Hence in the code which you have written , the program flow is :

Call to 2 arg constructor

  Call to 3 arg constructor

      Call to super class constructor

         Call to init block

      print 6

  print 11