In this article, we will learn about the order of execution of blocks in Java.
Different blocks and their order of execution 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();
}
}
The output of the above program
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 a class gets loaded.
But Anonymous block and Constructor will run every time the object of a class gets created. Init block will get executed first and then constructor.
Nice one
Static block executes only when the main method is called or every time the class gets executes .
Static block gets executed when class is loaded. It has nothing to do with mains method. When ever main method is called. Class gets loaded hence this behaviour.
Why “ananymous”? Why not “anonymous”?
anonymous is getting used only here.