The instance block is for write the logic's and also initialize variable(both are done during object creation time). This will be explained below examples.
Instance blocks are executed during the object creation time. Instance blocks are executed first that the constructor block.
Already Constructor Block is their to write logic's during the object creation time but what is the use of Instance Block, Constructor Block logic's is specific to object But Instance Block logic's is common to all objects.
The order of execution of Instance Block block is from Top to bottom. Instance Bock execution depends on object creation but not Constructor execution.
Example 1:
class Test
{
Test()
{
System.out.println("0-args Constructor");
}Test(int a)
{
System.out.println("1-args Constructor");
}
Test(int a,int b)
{
System.out.println("2-args Constructor");
}
{
System.out.println("Instance Block");
}
public static void main(String[] args)
{
System.out.println("In Main");
new Test();
new Test(12);
new Test(23,43);
}
}
Output:
In Main
Instance Block //executed first observe the code once
0-args Constructor
Instance Block // again executed for Test(12);
1-args Constructor
Instance Block //again
2-args Constructor
Example 2:
class Test
{
Test()
{
System.out.println("0-args Constructor");
}
{
System.out.println("Instance Block");
}
public static void main(String[] args)
{
System.out.println("In Main");
new Test();
}
}
Output:
In Main
Instance Block
0-args Constructor
Instance Block
0-args Constructor
Instance Block
0-args Constructor
Example 3:
class Test
{
Test()
{
System.out.println("0-args Constructor");
}
{
System.out.println("Instance Block 2");
}
Test(int a)
{
System.out.println("1-args Constructor");
}
{
System.out.println("Instance Block 1");
}
public static void main(String[] args)
{
System.out.println("In Main");
new Test();
new Test(12);
}
}
Output:
In Main
Instance Block 2
Instance Block 1
0-args Constructor
Instance Block 2
Instance Block 1
1-args Constructor
Note: The order of execution of Instance Block is from Top to bottom.
Example 4:
class Test
{
Test()
{ this(12);
System.out.println("0-args Constructor");
}
Test(int a)
{
System.out.println("1-args Constructor");
}
{
System.out.println("Instance Block 1");
}
public static void main(String[] args)
{
System.out.println("In Main");
Test t = new Test();
}
}
Output:
In Main
Instance Block 1
1-args Constructor
0-args Constructor
Note: Instance Block execution depends on object creation but not Constructor execution.
Example 5:
class Test
{
int a;
void disp()
{
System.out.println(a);
}
{
System.out.println("Instance Block 1");
a=555;
}
public static void main(String[] args)
{
System.out.println("In Main");
new Test().disp();
Test t = new Test();
t.disp();
}
}
Output:
In Main
Instance Block 1
555
Instance Block 1
555
Note: Instance block is used to initialize the local variables.
Output:
In Main
Instance Block 1
555
Instance Block 1
555
Note: Instance block is used to initialize the local variables.