- Static keyword can be applied to a block, { }, and they become static initialization block which runs only once when the class is first loaded by the JVM.
- This is used for initializing all the static variables and to perform any operations need to be executed when the class is loaded.
- They don’t return anything
- They don’t take any arguments
- They are executed in the order in which they appear in the class, i.e.) from top to bottom
- Syntax
static
{
//initialization code
}
Instance Initialization block | Static initialization block |
---|---|
Syntax:
|
Syntax:
|
It runs each time when an instance of the class is created | it runs only once when the class is first loaded by the JVM |
There can be more than one init block in a class and they are executed in the order they appear in the class | There can be more than one static block in a class and they are executed in the order they appear in the class |
Init blocks are executed right after the call to the super() in a constructor, i.e.) before the constructor of its own class runs | They are executed when the class is loaded from super class to sub class order. |
JVM throws java.lang.ExceptionInInitializerError if any exception occurs in static block static{ System.out.println(“In A’s static Block 1” + 10/0); } |
package com.ibytecode.keywords.staticdemo; class A { A() { System.out.println("In A's No-argument Constructor"); } A(String param) { System.out.println("In A's parameterized Constructor:" + param); } static{ System.out.println("In A's static Block 1"); } { System.out.println("In A's init Block 1"); } static{ System.out.println("In A's static Block 2"); } { System.out.println("In A's init Block 2"); } } class B extends A { B() { super(); System.out.println("In B's No-argument Constructor"); } B(String param) { super(param); System.out.println("In B's parameterized Constructor:" + param); } static{ System.out.println("In B's static Block 1"); } { System.out.println("In B's init Block 1"); } } public class StaticBlock { public static void main(String[] args) { new B(); new B("Param"); } }
In A’s static Block 1
In A’s static Block 2
In B’s static Block 1
In A’s init Block 1
In A’s init Block 2
In A’s No-argument Constructor
In B’s init Block 1
In B’s No-argument Constructor
In A’s init Block 1
In A’s init Block 2
In A’s parameterized Constructor:Param
In B’s init Block 1
In B’s parameterized Constructor:Param
How this works?
- In the main(), when we call the B() constructor, JVM needs to load class B and before loading it, it loads class A, since B extends A.
- Super class (A’s) static blocks runs first when the class is loaded
- Sub class (B’s) static blocks gets executed next
- Now it needs to run B’s no- argument constructor. Since there is a call to super(), A’s constructor should be executed first. Instance init blocks runs before A’s constructor.
- B’s init block runs then B’s constructor runs.