Static Block in Java | Example & Advantage

Static Initialization Block in Java


When a block is declared with the static keyword, it is called static block in Java. It is a normal block of code that is enclosed in braces ({ }) and is preceded by a keyword “static”. It is also known as static initialization block in Java.

The static block gets executed only once when the class is loaded into the memory by Java ClassLoader. The syntax to declare static block in Java program is as follows:

Syntax:

static {
   // Logic here or Java code.
 }

Why static block is executed before main method?


When we execute a particular class, JVM performs two actions at the runtime.
1. JVM loads corresponding dot class file (byte code) into memory.

2. During the dot class file loading into memory, static blocks are executed. After loading the dot class file, JVM calls the main method to start execution. Therefore, static block is executed before the main method.

In other words, we can also say that static block always gets executed first in Java because they are stored in the memory at the time of class loading or before the object creation.

How many times dot class file is loaded into memory?


Dot class file is loaded into the memory only one time. So, only one time static blocks will be executed. Instance block’s execution depends upon the object creation.

If we create 10 objects, 10 times instance blocks will be executed but the execution of static block depends upon the class loading. Since the class is loaded only one time So, static block will be executed only one time.

Let’s take an example program to understand this concept better.
Program source code 1:

package staticBlock; 
public class StaticBlockTest 
{ 
// Declare two instance blocks. 
   { 
     System.out.println("Instance block-1"); 
   } 
  { 
    System.out.println("Instance block-2"); 
  } 
// Declare two static blocks. 
 static { 
    System.out.println("Static block-1"); 
 } 
static { 
  System.out.println("Static block-2"); 
} 
// Declare zero parameter constructor. 
 StaticBlockTest()
 { 
   System.out.println("0-arg constructor"); 
 } 
// Declare one parameter constructor with int parameter named a. 
 StaticBlockTest(int a)
 { 
   System.out.println("1-arg constructor"); 
 } 
public static void main(String[] args) 
{ 
// Create an object of class. 
   new StaticBlockTest(); // Nameless object. 

// Create another object of class and pass an integer argument value. 
   new StaticBlockTest(20); // Nameless object. 
  } 
}
Output: 
        Static block-1 
        Static block-2 
        Instance block-1 
        Instance block-2 
        0-arg constructor 
        Instance block-1 
        Instance block-2 
        1-arg constructor

In the preceding example program, we have declared two instance blocks, two static blocks, two constructors, and created two objects. 

Since we have created two objects, so instance blocks will execute two times but the dot class file is loaded only one time into the memory. Therefore, only a one-time static block will be executed.


Key point:
Instance block and constructor both are executed during the object creation but instance block will execute first before the execution of the constructor during the object creation.

Instance Initialization Block in Java with Example 

Order of execution of multiple Static blocks in Java


A class can have any number of static initialization blocks that will execute in the same sequence as written in the program. i.e. The order of execution of multiple static initialization blocks is executed automatically from top to bottom during the dot class file loading.

Let’s take an example program to understand the order of execution of multiple static blocks and instance blocks declared in a class.
Program source code 2:
package staticBlock; 
public class MultipleStaticBlocks 
{ 
{ 
  System.out.println("Instance block-1"); 
} 
{ 
  System.out.println("Instance block-2"); 
} 
static { 
     System.out.println("Static block-1"); 
} 
static { 
     System.out.println("Static block-2"); 
} 
public static void main(String[] args) 
{ 
  new MultipleStaticBlocks(); 
 } 
}

The flow of execution of statements in the above program can be seen in the below figure.
Static block in Java

Output: 
       Static block-1 
       Static block-2 
       Instance block-1 
       Instance block-2

Can we execute static block without main method inside class?


It is possible to execute static block without a main method inside the class up to Java 1.5 version but Java 1.6 version onwards, the main method is mandatory to execute a static block inside the class. 

During the dot class file loading, first static blocks are executed and then JVM calls main method. Let’s take an example program where we will not declare main method in the class and see what happens? 
Program source code 3:

package staticBlock; 
public class Test 
{ 
static { 
  System.out.println("Hello Java"); 
 } 
static { 
    System.out.println("Welcome you"); 
  } 
}
Output: 
       Error: Main method not found in class staticblockExample.Test, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend JavaFX.application.Application

Use of Static block in Java


1. The purpose of using a static initialization block is to write that logic inside static block that is executed during the class loading.
2. It is mostly used for changing default value of static variables.
3. It is used to initialize static variables of the class.

Let’s create a program where we will change value of static variable inside static block.
Program source code 4:
package staticBlock; 
public class Employee 
{ 
   static String eName = "Deep"; 
   static int eID; 
   static int age; 
   String companyName = "TCS"; // Instance variable. 

// Change the value of static variable in the static initialization block. 
    static { 
       eName = "Shubh"; 
       System.out.println("Name of Employee: " +eName); 
    } 
// Initialize the value of static variable in the S.B. 
    static { 
       eID = 2342; 
       System.out.println("Employee's Id: " +eID); 
     } 
// If you don't assign the value of static variable then it will print default value. Here I am assigning any value to the employee's age. So it will print default value 'zero' on the console. Zero is the default value of an integer. 

static { 
     System.out.println("Employee's age: " +age); 
  } 
static { 
     System.out.println("Company name: " +companyName); // Compile time error because we cannot access not-static variables in the static block. 
  } 
public static void main(String[] args) 
{ 
  } 
}
Output: 
       Name of Employee: Shubh 
       Employee's Id: 2342 
       Employee's age: 0

Key point:
Static block cannot access instance (non-static) variables and methods. Let’s take an example program where we will try to access non-static variables and methods inside static block.

Program source code 5:

package staticBlock; 
public class MemberTest 
{ 
   static int a = 20; 
   int b = 30; // Instance variable 
// Declare instance method. 
    void display()
    { 
       System.out.println("Hello Java"); 
    } 
static void show()
{ 
   System.out.println("You cannot access instance variable in static method "); 
   System.out.println(b); // Compile time error because cannot make a static reference to the non-static field b. 
 } 
// Declare instance block. 
   { 
      display(); // Call the instance method. 
   } 
static 
{ 
   display(); // Compile time error because we cannot call instance method in static area. 
   System.out.println(a); // Calling S.V. 
   System.out.println(" " +b); // Compile time error because we cannot call instance variable in static block. 
 } 
public static void main(String[] args) 
{ 
   MemberTest mt = new MemberTest(); 
    mt.display(); 
    show(); 
  }
 }

Let’s create a program where we will define all five elements variable, method, constructor, instance block, static block within a class, and try to understand the order of execution. 

Program source code 6:

package staticBlock; 
public class AllTest 
{ 
  int x = 10; 
  static int y = 20; 
  void m1(int a)
  { 
     System.out.println("Instance method"); 
  } 
static void m2(String str)
{ 
   System.out.println("Static method"); 
 } 
AllTest()
{ 
   System.out.println("0-arg constructor"); 
} 
AllTest(int a)
{ 
   System.out.println("1-arg constructor"); 
 } 
 { 
    System.out.println("Instance block"); 
 } 
static { 
     System.out.println("Static block"); 
 } 
public static void main(String[] args) { 
    AllTest at = new AllTest(); 
    AllTest at2 = new AllTest(10); 
     at.m1(50); 
     AllTest.m2("Shubh"); 
  } 
}
Output: 
        Static block 
        Instance block 
        0-arg constructor 
        Instance block 
        1-arg constructor 
        Instance method 
        Static method

Advantage of Static block in Java


The advantages of static initialization block in Java are as follows:
1. Static initialization blocks are used to write logic that you want to execute during the class loading.
2. They are used to initialize the static variables.

Difference between Static block and Instance block in Java


1. Static block is also known as a static initialization block whereas instance block is also known as instance initialization block or non-static block.
2. They execute before the instance block whereas instance block executes after the static blocks.
3. Only static variables can be accessed inside the static block whereas both static and non-static variables can be accessed inside the instance block.
4. Static blocks execute when the class is loaded into the memory whereas instance blocks execute only when instance of the class is created.
5. ‘this’ keyword cannot be used in the static block whereas this keyword can be used in the instance block.

Final words
A static block can not be declared inside any method. It is automatically executed only once by JVM when the dot class file is loaded into the memory. If the keyword “static” is missed before block then the block is called non-static block (instance block) that is executed when class is instantiated.
Thanks for reading!!!

Next ⇒ Inner class in Java⇐ PrevNext ⇒

Leave a Comment