Java is an object-oriented, class-based programming language. Java is a high-level programming language that generally emphasizes minimizing the number of implementation dependencies. Java is also a static and general-purpose programming language. It lets the users utilize the concept of write once and run anywhere (WORA). This means that the compiled code can be run on any system having the Java Virtual Compiler (JVM). The Java Virtual Machine or JVM is used to convert the code into a machine-understandable byte code. Now that we know a little about Java let us discuss static blocks in Java.
Static Blocks in Java
Static blocks in Java can be created using the static keyword. The static blocks in Java are automatically called once every time a Java class executes. In the older versions of Java (1.6 and lower), static blocks in Java could be called without the main method, but in versions after 1.6, Java removed this feature. Making it compulsory for a class to have the main method.
Let us see an example of how to declare a static block in Java.
In Java, a static block (also known as a static initialization block) is a block of code that is run when the class is loaded into memory by the Java Virtual Machine (JVM). It's often used to initialize static variables.
Here is an example:
public class MyClass {
// Static variable
static int myVar;
// Static block
static {
myVar = 10;
System.out.println("Static block executed and myVar is " + myVar);
}
public static void main(String[] args) {
System.out.println("Main method executed and myVar is " + myVar);
}
}
When this program is run, the output will be:
Static block executed and myVar is 10
Main method executed and myVar is 10
This output shows that the static block was executed before the main method, at the time the class was loaded, and it was able to initialize the `myVar` variable.
Calling of Static Block in Java
In Java, a static block (also known as a static initialization block) is a block of code within a class that is executed only once when the class is first loaded into memory. It's typically used for initializing static variables, and it can also be used to perform any one-time computations or setup operations.
Here's the key point: A static block is not called by you or any other part of your code, it's automatically called by the Java Virtual Machine (JVM) when the class is loaded.
Consider the following example:
public class MyClass {
// Static variable
static int myVar;
// Static block
static {
myVar = 10;
System.out.println("Static block executed and myVar is " + myVar);
}
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println("Main method executed and myVar is " + myVar);
}
}
When we run this program, the static block will execute before the main method or any constructors, regardless of where it appears in the class, and it will execute only once, no matter how many objects of the class are created. So, the output will be:
Static block executed and myVar is 10
Main method executed and myVar is 10
Execution of Static Block in Java
The execution of a static block in Java is handled by the Java Virtual Machine (JVM). A static block, also known as a static initialization block, is a block of code within a class that is executed when the class is first loaded into memory.
Here's what happens:
When your program is run, the JVM loads the required classes into memory.
The class loader subsystem of JVM loads classes.
When a class is loaded into memory, if it contains any static blocks, those blocks are executed by the JVM, in the order that they appear in the class.
This execution happens only once, no matter how many objects of the class you create.
The main purpose of a static block is to initialize static variables, but they can also be used to perform any one-time setup or computation that needs to be done when the class is loaded, before any objects are created from it.
Here's an example:
public class MyClass {
// Static variable
static int myVar;
// First static block
static {
myVar = 10;
System.out.println("First static block executed and myVar is " + myVar);
}
// Second static block
static {
myVar = 20;
System.out.println("Second static block executed and myVar is " + myVar);
}
public static void main(String[] args) {
System.out.println("Main method executed and myVar is " + myVar);
}
}
When we run this program, the static blocks will be executed before the main method, in the order that they appear in the class, and they will only be executed once. So, the output will be:
First static block executed and myVar is 10
Second static block executed and myVar is 20
Main method executed and myVar is 20
Why is the Static Block Executed Before the Main Method?
In Java, the static block is executed before the main method because it's part of the class loading process. The Java Virtual Machine (JVM) goes through a specific sequence when a class is loaded. First, it loads static variables and static blocks, executing them in the order they appear in the class. The main method, being static itself, can only be called once the class is fully loaded and all static initializations are completed. Hence, static blocks are executed before the main method, preparing any necessary static data before any static methods (including main) are executed.
Order of Execution of Multiple Static Blocks in Java
In Java, if a class has multiple static blocks, they will be executed in the order they appear in the class.
When a Java class is loaded into memory, the Java Virtual Machine (JVM) processes static variables and static initialization blocks in the sequence they appear in the class code.
Consider the following example:
public class MyClass {
// First static block
static {
System.out.println("First static block");
}
// Second static block
static {
System.out.println("Second static block");
}
// Third static block
static {
System.out.println("Third static block");
}
public static void main(String[] args) {
System.out.println("Main method");
}
}
When we run this program, the static blocks will be executed in the order they appear before the main method. So, the output will be:
First static block
Second static block
Third static block
Main method
Remember that these blocks are only executed once when the class is loaded into memory, not every time an instance of the class is created.
Can we Execute the Static Block without the Main Method inside a Class?
In versions of Java before Java 7, it was possible to execute a static block without a main method. You could do this by using a static block to exit the program before the JVM reaches the point where it would normally call the main method. Here's an example:
public class MyClass {
static {
System.out.println("Static block executed");
System.exit(0);
}
}
In this example, the static block is executed and then the program is exited before a main method is called.
However, starting from Java 7, this no longer works. The JVM checks for the main method at the class loading time and will give an error if the main method is not found. So, in Java 7 and later, you must have a main method in your class if you want to run it as an application.
Use of Static Block in Java
The uses of static block in Java are:
Static blocks often find application in initializing static variables of a class with default values.
It is also used in loading the configuration settings from a database.
Static blocks are also used for initializing resources, establishing connections with external services, etc. These tasks are to be done only once during the entire program lifecycle.
It is also used to call static methods of a class.
Difference between Static Block and Instance Block in Java
The difference between static and instance block in java are:
Static block
Instance block
Static block is executed when a class in Java is loaded into the computer's memory.
Instance block is executed when an object of a class is created.
Static blocks are executed only once
Instance blocks are executed every time an object of a Java class is created.
Static blocks in Java cannot use this keyword
Instance blocks in Java can use this keyword.
Static blocks can only access the static members of a class.
Instance blocks can access both the static and instance variable and methods of the class.
Frequently Asked Questions
How many times static block is executed in Java?
Static block is executed only one time when the class is loaded into the computer's memory. They are executed before the class object is created or any static method or variable of a class is accessed.
What is static block, and why it is used?
A static block is a code block executed only one time when the class is loaded into the computer's memory. Static blocks are used for initializing static variables in the code.
What is the difference between static and non-static blocks?
Static blocks are used for initializing static variables in Java and are executed only once. It is mandatory to use the static keyword for that block of code. Non-static blocks are executed each time before the constructor is called. Non-static blocks are used for initializing the variables declared in the class.
Where are static blocks stored in Java?
All static blocks and variables are stored in the heap section of the memory. This section of memory is also called PermGem(Permanent Generation), in which all the data that belongs to the classes are stored.
Conclusion
This Blog covered all the necessary points about the static blocks in Java. We further looked at examples to understand static blocks in Java.
Try Coding Ninjas Studio for more exciting articles, interview experiences, and excellent Machine Learning and Python problems.