Static Block in Java | Use, Example

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”.

A static block is also known as static initialization block or static initializer block in Java. It gets executed only once by JVM when the class is loaded into the memory by Java ClassLoader.

We mainly use the static block to initialize static variables, set up resources, or perform any other tasks that need to be done before the class is used.

Syntax to Declare Static Initialization Block in Java


Static initialization blocks are enclosed within curly braces and are preceded by a keyword static. The general syntax to declare a static block in Java program is as follows:

static {
   // Logic here or Java code.
 }

Why Static Initialization Block is Executed before Main method?


When we execute a particular class, JVM performs two actions at the runtime. They are as:

1. JVM loads the corresponding dot class file (byte code) into memory.

2. During the dot class file loading into memory, static block is 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 it is stored in the memory at the time of class loading and before the object creation.

Let’s test which one is executed first, the static block, or static method by JVM with the help of an example program.

Program code 1:

package staticBlock;
public class Test 
{
// Static block declaration. 
   static { 
       System.out.println("Static block");
   }
public static void main(String [] args) {
     System.out.println("Main method");
 }
}
Output:
       Static block
       Main method

Explanation:

1. If the static block is present in the program, JVM execute it first of all. After complete execution, JVM searches for the main() method. If the main() method is not found, it will display an error at runtime.


2. If the static block is not present in the program, JVM invokes the main method first.

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 block will be executed. Instance block’s execution depends upon the object creation.

For example, 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 the static block will be executed only one time.

Let’s take an example program to understand this concept better.

Program code 2:

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 a parameter a of type int. 
   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

Explanation:

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

2. 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 one time static block will be executed.


Note:

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.

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. That is, 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 code 3:

package staticBlock; 
public class MultipleStaticBlocks 
{ 
// Instance blocks
   { 
      System.out.println("Instance block-1"); 
   } 
   { 
      System.out.println("Instance block-2"); 
   } 

// Static blocks.
   static { 
       System.out.println("Static block-1"); 
   } 
   static { 
       System.out.println("Static block-2"); 
   } 

public static void main(String[] args) 
{ 
    new MultipleStaticBlocks(); 
 } 
}

We have explained the flow of execution of statements of the above program 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 the main method in the class and see what happens?

Program code 4:

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 Initialization Block in Java


There are mainly three uses of static initialization block in Java that are as follows:

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

Let’s take an example program where we will change the value of static variables inside static initialization block.

Program code 5:

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

Note: 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 the static initialization block.

Program code 6:

package staticBlock; 
public class MemberTest 
{ 
   static int a = 20; 
   int b = 30; // Instance variable 

// Declare instance method. 
   void display()
   { 
      System.out.println("Hello Java"); 
   } 

// Declare static initialization block.
   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(); // Calling instance method. 
   } 
  static 
  { 
     display(); // Compile time error because we cannot call instance method in static area. 
     System.out.println(a); // Calling static variable.
     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 take an example 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 code 7:

package staticBlock; 
public class AllTest 
{ 
   int x = 10; 
   static int y = 20; 

// Instance method.  
   void m1(int a)
   { 
     System.out.println("Instance method"); 
   } 
// Static method.
   static void m2(String str)
   { 
      System.out.println("Static method"); 
   } 
// Constructors declaration.
   AllTest()
   { 
     System.out.println("0-arg constructor"); 
   } 
   AllTest(int a)
   { 
      System.out.println("1-arg constructor"); 
   }

// Instance initialization block. 
   { 
     System.out.println("Instance block"); 
   } 
// Static initialization 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 Initialization Block in Java


The advantages of static initialization block in Java are as follows:

  • Static initialization blocks are used to write logic that you want to execute during the class loading.
  • They are used to initialize the static variables.

Difference between Static block and Instance block in Java


The top five differences between instance block and static block in java are as follows:

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.


Key Points:

1. In Java, we cannot declare a static initialization block inside any method.

2. JVM executes a static block on the highest priority basis when the dot class file is loaded into the memory.

3. 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.


In this tutorial, we have explained the concepts of static initialization block in Java with the help of various example programs. Hope that you will have understood the basic concepts and practiced all programs. In the next, we will understand final keyword in Java with examples.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love