Static Block in Java | Use, Example

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

Static block is also known as static initialization block or static initializer block in Java.

The static block gets executed only once by JVM 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. 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 by JVM, the static block, or static method with help of an example program.

Program source code 1:

public class Test { 
 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.


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

Explanation:

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

2. Since we have created two objects, 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 source code 3:

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 the main method in the class and see what happens?

Program source 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 block in Java


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

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 the value of static variables inside static block.

Program source 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 block.

Program source 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"); 
  } 
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 method.
   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 7:

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


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. A static block in java can not be declared 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.
Thanks for reading!!!

Next ⇒ Final keyword in Java

⇐ PrevNext ⇒

Leave a Comment