Write a Java program to call static block using the anonymous object


This Java program defines two classes: CallStatic_Block and Demo. The CallStatic_Block class contains a main() method which creates a new instance of the Demo class using the new keyword. Both the CallStatic_Block and Demo classes also contain static blocks, which are executed when the class is loaded by the JVM.

Source Code

public class CallStatic_Block
{
	static
	{
		System.out.println("Static Block 1");
	}
	public static void main(String[] args)
	{
		new Demo();
	}
	static
	{
		System.out.println("Static Block 2");
	}
}
class Demo
{
	static
	{
		System.out.println("Static Block 3");
	}
	Demo()
	{
		System.out.println("Constructor");
	}
	static
	{
		System.out.println("Static Block 4");
	}
}

Output

Static Block 1
Static Block 2
Static Block 3
Static Block 4
Constructor