Static Block
Static block gets executed when the class is loaded into memory by the classloader. And it is executed only once. The main use of this block is to initialize the static data members of the class.
Some important points about static block
- Static block is executed at the time of loading of the class
- Static block is executed before invocation of the main method
- The main use of static block is to initialize the value of static data members of a class
- Any kind of initialization code can also be written inside static block which doesn’t depend on object creation of the class
syntax
static {
//some code
//some code
}
Static block example
package com.javatrainingschool;
public class StaticBlockExample {
static {
System.out.println("static block is executed just once");
System.out.println("static block is executed before main method call");
}
public static void main(String[] args) {
System.out.println("main method executed");
}
}
Output :
static block is executed just once
static block is executed before main method call
main method executed