Static Block in Java
In Java, the static keyword is used for the management of memory mainly. the static keyword can be used with Variables, Methods, Block and nested class. A static block in a program is a set of statements which are executed by the JVM (Java Virtual Machine) before the main method. At the time of class loading, if we want to perform any task we can define that task inside the static block, this task will be executed at the time of class loading. In a class, any number of a static block can be defined, and this static blocks will be executed from top to bottom.
Syntax:
Example of a static block
Static block executes before the main method while executing program. Statements written inside the static block will execute first. However both are static.
Â
Example of multiple static blocks
When we have multiple static blocks then each block executes in the sequence. First static block will execute first.
Â
Initializer Block in Java
In Java, the initializer Block is used to initialize instance data members. The initializer block is executed whenever an object is created. The Initializer block is copied into Java compiler and then to every constructor. The initialization block is executed before the code in the constructor.
Example:
Â
Example using static and initializer block
We can have both static and initializer blocks in a Java program. But static block will execute first even before initializer block. See the below example.
Â
Â