According to my knowledge, if we want to do something just before object creation we want to write that code in the instance block as it called before the constructor.
For instance:
public class TestInstanceBlock {
public static int x = 0;
public TestInstanceBlock() {
System.out.println("This is my Default Constructor");
}
{
System.out.println("This is my instance block");
x++;
}
public static void main(String[] args) {
TestInstanceBlock obj = new TestInstanceBlock();
System.out.println("The value of x is: " + x);
}
}
Output:
This is my instance block
This is my Default Constructor
The value of x is: 1
For above program, we can get the same output without using instance block by just writing the instance blocks code in the constructor.
For instance:
public class TestInstanceBlock {
public static int x = 0;
public TestInstanceBlock() {
System.out.println("This is my instance block");
x++;
System.out.println("This is my Default Constructor");
}
public static void main(String[] args) {
TestInstanceBlock obj = new TestInstanceBlock();
System.out.println("The value of x is: " + x);
}
}
Output:
This is my instance block
This is my Default Constructor
The value of x is: 1
So, then what will be the advantage to use instance block approach over constructor approach?