What are Blocks in Java?
- Blocks are the special type of containers in java language.
- It acts as a container for executable java statements.
- Blocks mainly perform special type of operations. e.g. Database connectivity, Server Configuration etc.
- Blocks are mainly classified into two types:
- Static Block
- Non static Block
Static Blocks
- We have to declare static blocks by using static keywords.
- We use static block mainly to develop business logic where outcome of the logic is same for all the users and it executes only once in a application lifecycle.
- If java class contains static block and main method then static block executes before the main method at the time of class loading.
- It is possible to create multiple static blocks inside the single java class.
- We can initialize static variables inside the static block.
Non static Blocks
- We declare non static blocks without using the static keyword.
- We use non static blocks to develop business logic which is common for all objects also, which executes multiple times in an application lifecycle.
- Non static blocks execute at the time of object creation.
- It is possible to declare multiple non static blocks inside the single java class.
- We can initialize non static as well as static members inside the non static block.
Example:
public class Demo {
//Syntax for static block
static{
//Executes at the time of class loading
System.out.println("STATIC BLOCK");
}
public static void main(String[] args) {
System.out.println("MAIN METHOD");
Demo d1=new Demo();
}
//Syntax for non static block
{
//Executes at the time of object creation
System.out.println("NON STATIC BLOCK");
}
}
Output:
STATIC BLOCK MAIN METHOD NON STATIC BLOCK
Difference between Methods and Blocks in Java
- Methods in Java are responsible to perform normal business logic operation whereas, blocks perform special operations.
- Developer is responsible to call the method explicitly for execution while blocks will be automatically executed by JVM.
- Every method is having an identity but blocks do not have any identity.
- We can pass parameters by using methods but it is not possible to pass input parameters for blocks.
- It is possible to return value from method whereas you cannot return a value from block.

