Master java skills

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

  1. Static block is executed at the time of loading of the class
  2. Static block is executed before invocation of the main method
  3. The main use of static block is to initialize the value of static data members of a class
  4. 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