Static block in Java

A static block in a program is a block which is associated with a static keyword. The static block executes when the classloader loads the class. A static block is invoked before the main() method in java.

Syntax:

.........
static {
.......statements
}
.......

Let us go through a static block example.

Static block in Java with Example

class StaticTest
{
	//static integer is declared
	static int num;

        //static block
	static
   
	{
		num = 100;	//assigned the value
		System.out.println("This is Static block!");
	}
}

//Main driver
public class Main
{
	public static void main(String args[])
	{
		//printing the num value, but will be printed atlast
		System.out.println(StaticTest.num);
	}
}

Output:

This is Static block!
100

As you can see, the static block is executed first, and then the Main function in the above program.