Static block also called initializer block is mostly used for changing the default values of static variables. The static block gets executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.
The static block gets executed very first before static and non static methods even before public static void main(String[] args).
Syntax:
static{
//body
}
Example:
class Test
{
// First static block
static{
System.out.println("From 1st static block");
}
// Second static block
static{
System.out.println("From 2nd static block");
}
// static method
static void m1(){
System.out.println("From m1() static method");
}
// main() method
public static void main(String[] args)
{
System.out.println("From main() method");
m1();
}
}
Output:-
From 1st static block
From 2nd static block
From main() method
From m1() static method
Static block always get executed before static method.
Static block cannot return a value.
Static block cannot be called explicitly.
Static block cannot throws an exception.
The this and super keywords cannot be used inside the static block.
If a class have multiple blocks then they will execute in the same order as they written.
If you’re loading drivers. For ex, Class class has a static block where it registers the natives.
If you need to do manipulation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded.
If you need a Map with static values.
If you need some common values like server url, IP address at very beginning of the program.
Security related issues or logging related tasks.
Example: Use two static blocks, one to initialize a Map having languages and another to create a file
import java.io.*;
import java.util.*;
class Test
{
static FileWriter out= null;
private static final HashMap<String,String> languages = new HashMap<String,String>();
// Initialize the Map inside static block
static{
languages.put("en","English");
languages.put("fr","French");
languages.put("hi","Hindi");
} // end of first static block
// create and open a log file not exist
static{
try
{
File f = new File("log.txt");
if(!f.exists()) // check whether log.txt available or not
{
f.createNewFile(); // create log.txt file
}
out = new FileWriter(f,true);
System.out.println("Log file is ready to write...");
}catch(Exception e)
{
e.printStackTrace();
}
} // end of second static block
// write log into a log file
public static void writeLog(String text)throws Exception
{
out.write(text);
out.flush();
}
// main() method
public static void main(String[] args)
{
try
{
System.out.println("language= "+languages.get("fr"));
writeLog("logging text");
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Output:- After executing above program, a log.txt file will be created and "logging Text" will be written inside
Log file is ready to write...
language= French
Let’s first understand the static members.
A static variable gets created at the time of class loading even before the execution of static block and static method.
The purpose of the static initialization block is to assign value to the static variables.
The purpose of the static method is to access / use static variable and to execute code without creating an object.
Consider you have a static variable serverUrl and you want to fetch the server url from database or a file and assign that value to the static variable serverUrl inside a static block. You have a static method which is using value of static variable serverUrl. If static method executed before static block then there will not be server url value assigned to the static variable serverUrl(you will get default value and not the value from the static block). To avoid this problem static block always gets executed before static method to ensure that the static variables will get value before their use.
Example:
class Test
{
static String serverUrl;
// First static block
static{
//get server url from database or a config file
serverUrl="http://www.topperskills.com";
}
// static method
static void sendData(){
//code to hit the url and send some data
System.out.println(serverUrl);// serverUrl variable must get value assigned from static block before printing here
}
// main() method
public static void main(String[] args)
{
sendData();
}
}
Output:-
http://www.topperskills.com
If you use a static method to initialize static variable then there is no guarantee that the static method will execute (before executing other methods) and assign value to the static variable before its use. Instead static initalizer block always execute before all methods therefore there is guarantee that instance variables get value before their use.