Blocks
A block is a pair of
{ }braces.It is used to group a set of statements.
A block can be declared:
Inside a class
Inside a method
Inside a constructor
Inside another block
Types of Blocks
Instance Block (Non-Static Block)
Static Block
Local Block
1. Instance Block (Non-Static Block)
A block declared inside a class without
statickeywordAlso called Non-Static Block
Executes when object is created
Runs before constructor
Can have multiple instance blocks
Execution order → top to bottom (as declared)
Can access:
Instance variables
Static variables
class A {
int a = 10; // instance variable
static int b = 20; // static variable
{
System.out.println("Instance Block 1");
System.out.println("a: " + a);
System.out.println("b: " + b);
}
{
System.out.println("Instance Block 2");
}
}
class Main {
public static void main(String[] args) {
new A();
new A();
}
}Output :
Instance Block 1
a: 10
b: 20
Instance Block 2Runs every time object is created
2. Static Block
A block declared with
statickeywordExecutes when class is loaded
Runs only once in program life cycle
Executes before main() method
Can directly access:
Static variables ✅
Instance variables ❌ (need object)
Used for:Initialization logic
Database connection setup
Configuration loading
class A {
static int b = 20;
static {
System.out.println("Static Block in A");
System.out.println("b: " + b);
}
int a = 10;
{
System.out.println("Instance Block in A");
}
}
class Main {
public static void main(String[] args) {
new A();
}
}Output:
Static Block in A
b: 20
Instance Block in AStatic block runs first, then instance block
Important Note (Execution Order)
class A {
static {
System.out.println("SB-1");
}
static int a = 10;
static {
System.out.println("SB-2");
System.out.println(a);
}
}Output:
SB-1
SB-2
10Execution depends on declaration order
3. Local Block
A block defined inside a method or local context
Executes when method is called
Not static or instance block
Used for:
Code grouping
Block-level operations
Synchronization (advanced use)
class A {
void m1() {
System.out.println("Before Local Block");
{
System.out.println("Inside Local Block");
}
System.out.println("After Local Block");
}
}
class Main {
public static void main(String[] args) {
new A().m1();
}
}Output:
Before Local Block
Inside Local Block
After Local BlockCombined Example
class A {
int a = 10;
static int b = 20;
static {
System.out.println("Static Block in A");
}
{
System.out.println("Instance Block in A");
}
}
class Main {
static {
System.out.println("Static Block in Main");
}
public static void main(String[] args) {
A a1 = new A();
}
}Output:
Static Block in Main
Static Block in A
Instance Block in A