Introduction
Initialization blocks are blocks of code that execute when an object is created or when a class is loaded. There are two types:
- Instance Initialization Block (IIB)
- Static Initialization Block (SIB)
Instance Initialization Block (IIB)
Syntax:
class ClassName {
{
// Instance initialization block
// Executed when object is created
}
}
Simple Example:
class Student {
String name;
int rollNo;
// Instance initialization block
{
System.out.println("Instance block executed");
name = "Unknown";
rollNo = 0;
}
Student() {
System.out.println("Constructor executed");
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
System.out.println(s.name);
}
}
Output:
Instance block executed
Constructor executed
Unknown
When IIB Executes
Executed:
- Every time an object is created
- Before constructor
- After parent class constructor (super())
class Demo {
{
System.out.println("IIB 1");
}
Demo() {
System.out.println("Constructor");
}
{
System.out.println("IIB 2");
}
}
public class Main {
public static void main(String[] args) {
Demo d1 = new Demo();
System.out.println();
Demo d2 = new Demo();
}
}
Output:
IIB 1
IIB 2
Constructor
IIB 1
IIB 2
Constructor
Static Initialization Block (SIB)
Syntax:
class ClassName {
static {
// Static initialization block
// Executed when class is loaded
}
}
Example:
class Database {
static String url;
static int port;
// Static initialization block
static {
System.out.println("Static block executed");
url = "localhost";
port = 3306;
}
Database() {
System.out.println("Constructor executed");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Creating first object");
Database db1 = new Database();
System.out.println("\nCreating second object");
Database db2 = new Database();
}
}
Output:
Static block executed
Creating first object
Constructor executed
Creating second object
Constructor executed
Note: Static block runs only once when class is first loaded.
Both Together
class Example {
static int staticVar;
int instanceVar;
// Static block
static {
System.out.println("1. Static block");
staticVar = 100;
}
// Instance block
{
System.out.println("2. Instance block");
instanceVar = 200;
}
// Constructor
Example() {
System.out.println("3. Constructor");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Creating object 1:");
Example e1 = new Example();
System.out.println("\nCreating object 2:");
Example e2 = new Example();
}
}
Output:
1. Static block
Creating object 1:
2. Instance block
3. Constructor
Creating object 2:
2. Instance block
3. Constructor
Execution Order
class Order {
static int a = 10; // 1. Static variable initialization
int b = 20; // 3. Instance variable initialization
static { // 2. Static block
System.out.println("Static block: a = " + a);
a = 100;
}
{ // 4. Instance block
System.out.println("Instance block: b = " + b);
b = 200;
}
Order() { // 5. Constructor
System.out.println("Constructor: a = " + a + ", b = " + b);
}
}
Order:
- Static variable initialization
- Static block
- Instance variable initialization
- Instance block
- Constructor
Multiple Blocks
class Multiple {
static {
System.out.println("Static block 1");
}
{
System.out.println("Instance block 1");
}
static {
System.out.println("Static block 2");
}
{
System.out.println("Instance block 2");
}
Multiple() {
System.out.println("Constructor");
}
}
Output (first object):
Static block 1
Static block 2
Instance block 1
Instance block 2
Constructor
Blocks execute in the order they appear.
Use Cases
1. Common Initialization for All Constructors:
class Student {
String name;
int rollNo;
static int counter = 0;
// Instance block - common for all constructors
{
counter++;
System.out.println("Student #" + counter + " created");
}
Student() {
this.name = "Unknown";
this.rollNo = counter;
}
Student(String name) {
this.name = name;
this.rollNo = counter;
}
}
2. Complex Static Initialization:
class Config {
static Map<String, String> properties;
static {
// Complex initialization
properties = new HashMap<>();
properties.put("host", "localhost");
properties.put("port", "8080");
properties.put("protocol", "http");
}
}
3. Loading Resources:
class Database {
static Connection connection;
static {
try {
// Load driver and connect
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db");
System.out.println("Database connected");
} catch (Exception e) {
System.out.println("Connection failed");
}
}
}
Complete Example
class BankAccount {
private static int totalAccounts = 0;
private static double totalBalance = 0;
private String accountNumber;
private String holderName;
private double balance;
// Static block
static {
System.out.println("=== Bank System Initialized ===");
totalAccounts = 0;
totalBalance = 0;
}
// Instance block
{
totalAccounts++;
System.out.println("Creating account #" + totalAccounts);
}
// Constructor
public BankAccount(String accountNumber, String holderName, double balance) {
this.accountNumber = accountNumber;
this.holderName = holderName;
this.balance = balance;
totalBalance += balance;
System.out.println("Account created: " + accountNumber);
}
public static void showStats() {
System.out.println("Total Accounts: " + totalAccounts);
System.out.println("Total Balance: " + totalBalance);
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc1 = new BankAccount("1001", "John", 5000);
System.out.println();
BankAccount acc2 = new BankAccount("1002", "Alice", 3000);
System.out.println();
BankAccount.showStats();
}
}
With Inheritance
class Parent {
static {
System.out.println("Parent static block");
}
{
System.out.println("Parent instance block");
}
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
static {
System.out.println("Child static block");
}
{
System.out.println("Child instance block");
}
Child() {
System.out.println("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
}
}
Output:
Parent static block
Child static block
Parent instance block
Parent constructor
Child instance block
Child constructor
Comparison
| Feature | Instance Block | Static Block |
|---|---|---|
| Keyword | None (just {}) | static {} |
| Executes | Every object creation | Once when class loads |
| When | Before constructor | Before any static access |
| Access | Instance + static members | Only static members |
| Use | Common instance initialization | Static initialization |
| Can throw | Checked exceptions (with constructor) | Must handle exceptions |
Instance Block vs Constructor
| Instance Block | Constructor |
|---|---|
| No name | Has name (class name) |
| No parameters | Can have parameters |
| Always executes | One constructor executes |
| Executes before constructor | Executes after instance block |
| Cannot be called directly | Can be overloaded |
Exception Handling
Instance Block:
class Example {
{
try {
// Code that may throw exception
int x = 10 / 0;
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Static Block:
class Example {
static {
try {
// Must handle exceptions
Class.forName("SomeClass");
} catch (ClassNotFoundException e) {
System.out.println("Class not found");
}
}
}
Counter Example
class Counter {
static int classCounter = 0;
int objectCounter = 0;
static {
System.out.println("Class loaded");
}
{
classCounter++;
objectCounter++;
System.out.println("Object created: " + classCounter);
}
void display() {
System.out.println("Class counter: " + classCounter);
System.out.println("Object counter: " + objectCounter);
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
c1.display();
Counter c2 = new Counter();
c2.display();
}
}
Quick Reference
class Example {
// Static block
static {
// Runs once when class loads
// Initialize static members
}
// Instance block
{
// Runs every object creation
// Before constructor
// Initialize instance members
}
// Constructor
Example() {
// Runs after instance block
}
}
Benefits
- Code Reuse: Common code for all constructors
- Initialization: Complex static/instance setup
- Resource Loading: Load resources once (static)
- Counter: Track object creation
- Exception Handling: Handle initialization errors
When to Use
Use Instance Block:
- Common initialization for multiple constructors
- Complex instance setup
- Anonymous classes
Use Static Block:
- Static variable initialization
- Load resources (files, drivers)
- One-time setup
- Exception handling during static init
Exam Tips
Remember:
- Instance block executes every object creation
- Static block executes once when class loads
- Instance block runs before constructor
- Static block runs before instance block
- Multiple blocks execute in order
- Static block cannot access instance members
- Instance block can access static members
- Used for common initialization
- Execute in order: Static → Instance → Constructor
- With inheritance: Parent static → Child static → Parent instance → Parent constructor → Child instance → Child constructor
Common Questions:
- What is initialization block?
- Types of initialization blocks?
- When does static block execute?
- When does instance block execute?
- Execution order?
- Instance block vs constructor?
- Can static block access instance members?
- Use cases of initialization blocks?