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);
- }
- }
Example of Multiple Static Blocks
The following is an example of multiple static blocks:


Comments
Join the conversation! Your thoughts help the community grow.