Blocks in Java

Java blocks are enclosed within curly braces { and } and are mainly executed as single statements. Java blocks are executed from top to bottom. There are two types of blocks that Java supports.

  1. Static block
  2. Non Static block

Static Block

  • If a block is declared with a static keyword then it is known as a static block.
  • Static blocks are always executed before the main method and are called by JVM.
  • As the main method is called by JVM, static blocks are always executed for a single time.
  • Static is a class level variable.
  • Instance is an object level variable.
public class Test {
	static{
		System.out.println("Static Block");
	}

	public static void main(String[] args) {
		System.out.println("Main method");
		
	}

}
//First static block is executed then the main method is executed.

Non Static Block

  • If the block is declared without any static keyword then it is known as a non-static block.
  • Non-static blocks are always executed before the constructor.
  • Execution of multiple static/non-static blocks is from top to bottom.



public class Test {
	static{
		System.out.println("Static Block");
	}
	Test (){
		System.out.println("Constructor");
	}
	{
		System.out.println("Non-static block");
	}

	public static void main(String[] args) {
		System.out.println("Main method");
		new Test();
		new Test();
		
	}

}

//OUTPUT
/*Static Block
Main method
Non-static block
Constructor
Non-static block
Constructor
*/

Did you know?

Execution of non-static block depends on the user but the execution of static block depends on JVM.

Memory is always allocated when a object is created and while loading a class.