In this tutorial, we will learn about Instance block in Java. Instance blocks are used to initialize instance variables of the class. These blocks run every time when we create an object of the class. There are few things to note about instance blocks.
Page Contents
- we do not right any identifier with instance block
- instance block run every time we create an object of class
- it is not mandatory to create instance block in each class
- instance blocks run even before the constructor when we create an object of the class.
Example Program:
class Example{
//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[]){
Example obj=new Example();
Example obj2=new Example();
}
}
Output:
This is instance block
This is constructor block
This is instance block
This is constructor block
In above example you can see we have created two object of class and every time instance block is running before the constructor.
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.
