Instance Initializer Block in Java

In Java, we can execute code in constructors, methods, and blocks. A block is a group of zero or more statements between curly braces and can be used anywhere a single statement is allowed.

Syntax:

{
	this.num1 = 10;
 	this.num2 = 20;
	this.num3 = 30;
}

A block can be defined by two types:

1. Static Initialization Block:

static blocks are declared as static keyword and it runs first when a class loads and shared between all the objects. Static blocks are mainly used to perform the initialization of all static members of the class. It is also used to write the code we want to execute when the class loads i.e. loading property files.

static
{
	// code here
}

2. Instance Initialization Block:

instance blocks are associated with the object and that is the part of the class. It runs every time when a new object is created. Instance blocks are mainly used to perform initialization of instance data members of the class.

{
	//code here
}

class Car{  
    int speed;  
      
    Car(){System.out.println("speed is "+speed);}  
   
    {speed=100;}  
       
    public static void main(String args[]){  
    Car c1=new Car();  
    Car c2=new Car();  
    }      
}
Example Output

Share