Here we will learn to see the order of execution of blocks in Java.
Different block in Java Class
- Static Block
- Init Block(Anonymous Block)
- Constructor
/*
* Here we will learn to see how the different part (Ananymous Block, Constructor and Static Block ) of class will behave
* and what would be the order of execution.
*/
class JBTCLass {
/*
* Here Creating the Ananymous Block
*/
{
System.out.println("Inside Ananymous Block");
}
/*
* Now Creating the Static Block in Class
*/
static {
System.out.println("Inside Static Block");
}
/*
* Here Creating the Constructor of Class
*/
JBTCLass() {
System.out.println("Inside Constructor of Class");
}
public static void main(String[] args) {
// Creating the Object of the Class
JBTCLass obj = new JBTCLass();
System.out.println("*******************");
// Again Creating Object of Class
JBTCLass obj1 = new JBTCLass();
}
}
Output of the above programme
Inside Static Block
Inside Ananymous Block
Inside COnstructor of Class
*******************
Inside Ananymous Block
Inside COnstructor of Class
As you can see STATIC block will execute only once when class get loaded. But Anonymous block and Constructor will execute every time object of a Class gets created.