Introduction
In Java, we have a special block known as a Static Initialization Block. A Static Initialization Block is executed before the main( ) method. This is the main advantage of the Static Initialization Block in Java.
Static Initialization Block in Java
The following describes the Static Initialization Block in Java:
- A Static Initialization Block in Java is a block that runs before the main( ) method in Java.
- Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.
- In the entire program, the Static Initialization Block will execute only one time.
- There can be many Static Initialization Blocks in a specific class.
- If we have many Static Initialization Blocks in Java then they are called in a manner in the order they are written in the program.
- This block will not return anything.
- Checked exceptions cannot be thrown.
- We cannot use the "this" keyword since it does not have any instance.
Syntax
static
{
.......
.......
.......
}
Example of Static Block
- package demo;
- public class Demo
- {
- static double percentage;
- static int rank;
- static
- {
- percentage = 44.6;
- rank = 12;
- System.out.println("STATIC BLOCK");
- }
- public static void main(String args[])
- {
- Demo st = new Demo();
- System.out.println("MAIN METHOD");
- System.out.println("RANK: " + rank);
- }
- }
Output
Example of Multiple Static Blocks
The following is an example of multiple static blocks:
- package demo;
- public class Demo
- {
- static
- {
- System.out.println("FIRST STATIC BLOCK");
- }
- static
- {
- System.out.println("SECOND STATIC BLOCK");
- }
- static
- {
- System.out.println("THIRD STATIC BLOCK");
- }
- public static void main(String[] args)
- {
- }
- }
Output
Memory Management of Static Block
The following is an example of memory management of a static block:
- package demo;
- public class Demo
- {
- static int i;
- static
- {
- i=20;
- }
- static void print()
- {
- System.out.println(i);
- }
- public static void main(String[] args)
- {
- print();
- i=200;
- print();
- }
- }
Output
A Static Initialization Block is not stored on the heap, above in the figure it is clearly visible. It is not stored on the heap because it is executed only once. That is also the reason for the output for the preceding program.
Summary
This article explains the Static Initialization Block in Java.