Blocks in Java
A block in Java is a group of statements enclosed within curly braces {}
. Blocks define the scope of variables and control execution flow.
Types of Blocks in Java
Java has several types of blocks:
- Instance Initialization Block (IIB)
- Static Initialization Block (SIB)
- Method Block
- Loop and Conditional Blocks
- Synchronized Block
- Try-Catch-Finally Block
1. Instance Initialization Block (IIB)
- Runs before the constructor.
- Executes every time an object is created.
- Used to initialize instance variables.
Example: Instance Initialization Block
class Example {
int instanceVar;
// Instance Initialization Block
{
instanceVar = 42;
System.out.println("Instance Initialization Block executed.");
}
Example() {
System.out.println("Constructor executed.");
}
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
}
}
Output
Instance Initialization Block executed.
Constructor executed.
Instance Initialization Block executed.
Constructor executed.
Notice: The IIB runs before the constructor, and it runs for each object creation.
2. Static Initialization Block (SIB)
- Runs only once when the class is loaded into memory.
- Used to initialize static variables.
Example: Static Block
class Example {
static int staticVar;
// Static Initialization Block
static {
staticVar = 100;
System.out.println("Static Block executed.");
}
Example() {
System.out.println("Constructor executed.");
}
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();
}
}
Output
Static Block executed.
Constructor executed.
Constructor executed.
Notice: The static block runs only once, no matter how many objects are created.
3. Method Block
- A block inside a method.
- Used for defining logic.
- Variables declared inside the method block are local variables.
Example
class Example {
void myMethod() {
System.out.println("Inside method block.");
{
int localVar = 20; // Local variable
System.out.println("Inside inner block, localVar = " + localVar);
}
// System.out.println(localVar); // ERROR: localVar is out of scope
}
public static void main(String[] args) {
new Example().myMethod();
}
}
Output
Inside method block.
Inside inner block, localVar = 20
Scope Rule: The localVar
inside the inner block is not accessible outside.
4. Loop and Conditional Blocks
- Blocks inside if, else, while, for, switch-case, etc.
- Used to control execution flow.
Example: Loop & Conditional Block
public class Example {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("Positive Number");
} else {
System.out.println("Non-Positive Number");
}
for (int i = 0; i < 3; i++) {
System.out.println("Loop iteration: " + i);
}
}
}
Output
Positive Number
Loop iteration: 0
Loop iteration: 1
Loop iteration: 2
5. Synchronized Block
- Used in multithreading to allow only one thread to access a critical section at a time.
- Helps prevent race conditions.
Example: Synchronized Block
class Example {
void printNumbers() {
synchronized (this) { // Synchronizing the block
for (int i = 1; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try { Thread.sleep(100); } catch (InterruptedException e) {}
}
}
}
public static void main(String[] args) {
Example obj = new Example();
Thread t1 = new Thread(obj::printNumbers, "Thread-1");
Thread t2 = new Thread(obj::printNumbers, "Thread-2");
t1.start();
t2.start();
}
}
Ensures that only one thread can execute the synchronized block at a time.
6. Try-Catch-Finally Block
- Used for exception handling.
- Ensures that code inside
finally
always executes.
Example: Try-Catch-Finally
public class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block always executes.");
}
}
}
Output
Exception caught: java.lang.ArithmeticException: / by zero
Finally block always executes.
Even if an exception occurs, the finally
block runs.
Final Thoughts
✔ Instance Blocks (IIB) → Run before constructors, for initializing instance variables.
✔ Static Blocks (SIB) → Run once when the class is loaded, for initializing static variables.
✔ Method Blocks → Define logic inside a method.
✔ Loop & Conditional Blocks → Control flow of execution.
✔ Synchronized Blocks → Ensure thread safety in multi-threaded programs.
✔ Try-Catch-Finally Blocks → Handle exceptions and guarantee execution of finally
.