Static block in java

In this post, we learn about the static block. You must have seen various use of static keyword in java. We have already posted the static variable and static method. So, let’s introduce another interesting topic that is Static Block In Java.

Here is the table content of the article will we will cover this topic.

1. What is the static block in java?
2. How to create a static block?
3. How do the multiple static blocks?
4. Static block and method main?
5. Static block and constructor?
6. Static block and instance block (Non-static block)?
i) When it will get executed?
ii) What keyword should be used?
iii) Which type of data can be used?
7. Use of static block in real-time?
i) Perform operation during class loading?
ii) Use to initialize the static final variable?

static block in java

What is the static block in java OR java static initializer block?

In java, we can use the static keyword with a block of code that is known as a static block. A static block can have several instructions that always run when a class is loaded into memory. It is also known as java static initializer block because we can initialize the static variables in the static block at runtime. A class can have any number of static blocks, The JVM executes them in sequence in which they have written.  The static block in a program always executed first before any static method, non-static method, main method, or even instance block. Suppose we want to perform some operations at the time of class loading then we should use the static block should.

NOTE:  The static block always executes only one time when a class loaded into memory.

How to create a static block?

To create a static block in java we need to use the static and with the block. We can create a static block only at the class level. We can create a static block inside a method or constructor.
It creates with a keyword “static” and uses the curly braces  “{“ to start and end “}” the block.

static 
{
    // Body of static block
}

Where static is a keyword that is used to create a static block.
and Body of static block – The static block can contain only those code that belongs to static. It means we can’t use any non-static code here. In a static block, we can initiate the values of the static block and we can also invoke the static method. Because the static method is bound to class instead of the object. You can read “How static method binds with class”.

public class MainClass
{
	static int b;
	public static void show()
	{
		System.out.println("Static method");
	}
	static
	{
		b = 5;
		show();
	}
	public static void main(String arg[])
	{
		System.out.println("Main method");
	}
}

Output: Static method
Main method

How do the multiple static blocks?

A class can have any number of static blocks that will execute when class loaded in memory. Now the question arises what is the sequence of execution? Which method will be executed first?

The sequence of execution depends on the sequence as written in the program. The JVM will execute each static block one by one, which means the first static block executes before the second static block and so on. There is the reason behind to execute them one by one or in sequence. Because we can initialize a static variable in the first block and override it in the second block.

public class MainClass
{
	static int b;
	public static void show()
	{
		System.out.println("Static method");
	}
	static
	{
		b = 5;
		System.out.println("Value of b : " + b);
		show();
	}
	static 
	{
		b = 10;
		System.out.println("Value of b : " + b);
	}
	
	public static void main(String arg[])
	{
		System.out.println("Main method");
	}
}

Output: Value of b : 5
Static method
Value of b : 10
Main method

Static block and method main

The main method of a class is the entry point of execution. After the competition of class loading, JVM starts the execution from the main method. But a static block is a block of code that runs only once when a class is loaded into memory. It is also called a static initialization block because it is used to initialize the variables at run time.
So, when the JVM loads the class into memory it executes the static block.  Because static because doesn’t depend on object creation of the class. But the main method always executes after the complete loading of class.  Let’s see it with an example.

public class MainClass
{
	static int a = 5;
	static
	{
		a = a+5;
		System.out.println("Value of a : "+ a);
		System.out.println("Executing static block");
	}
	
	public static void main(String arg[])
	{
		System.out.println("Value of a : "+ a);
		System.out.println("Executing Main method");
	}
}

Output: Value of a : 10
Executing static block
Value of a : 10
Executing Main method

Static block and constructor

Whenever we create an object of the class by use of a new keyword the JVM calls a constructor.  A constructor is used to invokes non-static variables and methods of the class. JVM invokes a constructor after completion of class loading.  On another hand, static block executes at the time of class loading. It means JVM will run static block first, after that it will move to constructors.

Let’s take an example of a constructor and static block together. Here we will create a static block and a constructor that will print some data.  Let’s see how JVM handles these things during the execution.

public class MainClass
{
	static int a = 5;
	static
	{
		a = a+5;
		System.out.println("Value of a : "+ a);
		System.out.println("Executing static block");
	}
	MainClass()
	{
		System.out.println("Executing Constrcutor");
	}
	
	
	public static void main(String arg[])
	{
		System.out.println("Executing Main method");
	}
}

Output: Value of a : 10
Executing static block
Executing Main method

Static block and instance block (Non-static block)

A class can have static blocks and non-static blocks(Instance blocks). Both sections execute before the constructor. But both have different purposes and execution time. Let discuss it in detail.

When it will get executed?

The static block executes at class loading time because it can contain only static data that binds with class. So, there is no dependency on object creation.  
But the non-static block(Instance block) executes when the object is created. Because it can have non-static members that bind with the object. A non-static block always runs after the static block.

NOTE:  A non-static block doesn’t get execute if we will not create an object. It gets invoked only when an object created by JVM.

public class MainClass
{
	static int a = 5;
	static
	{
		System.out.println("Executing static block");
	}
	{
		System.out.println("Executing non-static block");
	}
	MainClass()
	{
		System.out.println("Executing Constrcutor");
	}
	
	
	public static void main(String arg[])
	{
		System.out.println("Executing Main method");
	}
}

Output: Executing static block
Executing Main method

You have seen in the above example, the non-static block is not get executed. The JVM always invokes a non-static block when it executes the constructor of the class. We haven’t provided any constructor in the above example.

 Let’s see how JVM executes it when we create a constructor of class.

public class MainClass
{
	static
	{
		System.out.println("Executing static block");
	}
	{
		System.out.println("Executing non-static block");
	}
	MainClass()
	{
		System.out.println("Executing Constructor");
	}
	
	
	public static void main(String arg[])
	{
		MainClass obj = new MainClass();
		System.out.println("Executing Main method");
	}
}

Output: Executing static block
Executing non-static block
Executing Constructor
Executing Main method

What keyword should be used?

To create a static block we must use the static keyword. The static keyword is prefixed before the start of the block. On another hand, we don’t need any keyword to create non-static (Instance block).

Which type of data can be used?

A static block can access any static variables or invokes static methods. But we can use any non-static variable or invokes any non-static methods.
A non-static block(Instance block) can access non-static and static variables as well. We can invoke any method either it is static or non-static.

Use of static block in real-time?

There are number of scenarios when we should use the static block. We will discuss those one by one. After that we can easily decide when to use the static block or not.

Perform operation during class loading

A static block is used to perform operations during class loading. You can perform operations that you want to do before the constructor. You can initialize the static variable or invokes static methods in the static block.

We can take an example of our JDK. Here we have class “Class” that is using static block to call a method registerNatives(). This method performs some necessary operation during the loading of classes.  

Let’s take another example. The static block can be used to initialize static variables.  Now you are thinking we can initialize the static variable during the declaration. But there may be a chance when the static variable is too complicated to be set up with a one-line declaration.

Scenario 1: There may be a case when the initialization of the static variable is depending upon other operations.

Suppose you want to set up resources on the loading of classes. So that resources will be available after the completion of class loading. You can make a static variable of that resource, so that is can access directly by class name and common for all the objects.

Suppose you want to load some drivers during class loading or maybe you want to create the connection of JDBC.

public class StaticBlockExample
{
	public static String connetion;
	public static String loadDriver;
	
	static
	{
		System.out.println("Creating connection and loading the driver");
		connetion =  CreateConnection();
		loadDriver = LoadDriver();
	}

	static String CreateConnection()
	{
		// Code to create a connection
		return "SQLConnection";
	}
	
	static String LoadDriver()
	{
		// Code to load the drivers
		return "LoadDriver";
	}
	
	public static void main(String arg[])
	{
		System.out.println("Using the connection and driver");
		System.out.println("Is connection ready :"+ connetion);
		System.out.println("Is driver loaded :"+ loadDriver);
	}
}

Output: Creating connection and loading the driver
Using the connection and driver
Is connection ready :SQLConnection
Is driver loaded :LoadDriver

Scenario 2: Sometimes a class has static variables that have complex initialization and that can’t be cover in a single line.

To make our code in a more readable form we should use a static block to initialize them. Suppose we want to declare and initialize a static HashSet and HashMap. If we declare it in a single line, it looks complex.

public static Map<Integer, String> hashMap = new HashMap<Integer, String>()
{{
	put(1, "One");
	put(2, "Two");	
	put(3, "Three");
}};
public static Set<String> hashSet = new HashSet<String>()
{{
	    add("a");
	    add("b");
	    add("c");
}};

We can use the static block to make code readable and initialize the static variable.

public class StaticBlockExample
{
	public static Map<Integer, String> hashMap = new HashMap<Integer, String>();
	public static Set<String> hashSet = new HashSet<String>();
	
	static
	{
		hashMap.put(1, "One");
		hashMap.put(2, "Two");	
		hashMap.put(3, "Three");
		
		hashSet.add("a");
		hashSet.add("b");
		hashSet.add("c");
	}
	
	public static void main(String arg[])
	{
		StaticBlockExample obj = new StaticBlockExample();
		System.out.println("HashMap values : "+ hashMap);
		System.out.println("HashSet values : "+ hashSet);
		System.out.println("Executing Main method");
	}
}

Output: HashMap values : {1=One, 2=Two, 3=Three}
HashSet values : [a, b, c]
Executing Main method

Use to initialize the static final variable

You can initialize a final variable in static block, but it should be static also. But static final variables can’t be assigned value in the constructor. So, they must be assigned a value with their declaration.

1. If you are not initializing a static final variable during the declaration(blank static final variable) then it must be initialized in static block otherwise compiler throws an exception at compile time.

2. A static final blank variable can’t be initialized in constructor. It must be initialized in static block.

public class Person
{
    String name;
    String address;
    static final String COUNTRYNAME;
    
    static
    {
        COUNTRYNAME = "India";
    }
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    void showData(Person person)
    {
        System.out.println("Name of Person : " + person.getName());
        System.out.println("Address of person : " + person.getAddress());
        System.out.println("Country of person : "+  person.COUNTRYNAME);
    }
    
    public static void main(String arg[])
    {
        Person person1 =  new Person();
        person1.setName("Ram");
        person1.setAddress("India");
        person1.showData(person1);
        
        Person person2 =  new Person();
        person2.setName("John");
        person2.setAddress("USA");
        person2.showData(person2);
    }
}

Output: Name of Person : Ram
Address of person : India
Country of person : India
Name of Person : John
Address of person : USA
Country of person : India

1 thought on “Static block in java”

Leave a Comment