In this tutorial, we will learn about Static block in Java. A very important thing about the static block is the static block belongs to class not to instance. That’s why static block only runs once it doesn’t matter how many numbers of instance we create. There are few things to note about the static block in Java.
Page Contents
- We do not use any identifier with static block but we use static keyword.
- Static block only runs once.
- Static block can even run even without creating an object of the class.
- Static block runs before the constructor and instance bock of the class.
Example Program
class Example{
//Static Block
static{
System.out.println("This is static block");
}
//Constructor
public Example(){
System.out.println("This is constructor block");
}
//main method
public static void main(String args[]){
}
}
Output:
This is static block
As you can see we haven’t even created a single object of the class still our static block is running. Here is another example to show what if we will create constructor and instance blocks in class.
Example Program
public class Example{
//Static Block
static{
System.out.println("This is static block");
}
//Instance Block
{
System.out.println("This is instance block");
}
//Constructor
public Example(){
System.out.println("This is constructor block");
}
//main method
public static void main(String args[]){
new Example();
new Example();
new Example();
}
}
Output:
This is static block
This is instance block
This is constructor block
This is instance block
This is constructor block
This is instance block
This is constructor block
As you can see in above example static block is only running once. On the other hand instance block and constructor running three time because we have created three objects of class.
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
