What are Static Initialization Blocks in Java?
Static initialization blocks in Java are the special blocks used for initialization of Static members of the Class. This block of code is executed when the Class gets loaded by the Class Loader. A Class can have any number of Static Initialization Blocks, and they can appear anywhere in the Class body. The Java run-time guarantees that static initialization blocks are called in the order that they appear in the source code.
Static Initialization Blocks can be declared in Java by writing the following block
Static Block Syntax
Tricky Interview Questions
Questions regarding Static Initialization Blocks has been asked most often at interviews. However, the most commonly asked question is “Does the Static Block declared in a Class with a Main method will be called before the Main method or after?”. And the answer to this is, before.
Yes, if you’re new to Static Blocks, you’ll be left confused because, most times in your career you must’ve heard that the entry point to a Java application is through the Main method, so how come static block will be called before it.
The reason why the static block is called before the Main method is because Java will run the static initializers of Class before any method is called or instance is created. Follow the reference for detailed information.
Following is the output of the above Class:
1. Inside Static Block
2. Inside Main Method
Now you know why the code inside the static block gets executed before the Main method, remember it during your Java interviews.
Points to Remember:
- Static blocks will be executed only once as soon the class is loaded in memory.
- They are executed in the order which they appear in the class.
- You cannot refer to any instance variables from within the static blocks.
- There is a limitation of JVM that a static initializer block should not exceed 64K.
- You cannot throw Checked Exceptions.
I hope this article will help you to grasp this short but tricky concept. Please leave a comment in the below comment box in case of any query.