Pages

Static,Instance,Constructor Blocks in java

What are the different types of Blocks available in java?

Block: It means a set of statements.

Below are types of blocks in java:

1) Static
2) Instance
3) Constructor

Static Block: 
  • This block will execute whenever a class is loaded. i.e., irrespective of object creation for a class it will execute.  
  • This block will only 1 time when class loaded.
For example, please see below sample code:


Static block

Instance Block:  This block will execute whenever the object of a class gets created. It is also called an Anonymous block.

Constructor: This block will execute whenever the object of a class gets created. If we have both Instance and Constructor are present in a class, then at first Instance block is executed then the constructor is executed.

Please see below sample program:


Java_Blocks


Preferences of execution of blocks:

1) If static blocks are present at first, Static block is executed, then go to next step
2) If instance blocks are present, instance blocks will execute, then go to next step
3) If constructor is present, constructor will execute.


##sample demo program ###

public class BlocksDemo {
// creating static block
static {
System.out.println("static block 1 is executed");
}
static {
System.out.println("static block 2 is executed");
}
//creating instance block
{
System.out.println("instance block 1 is executed");
}

//creating constructor
BlocksDemo() {
System.out.println("Constructor is executed");
{
System.out.println("Instance block in Constructor is executed");
}
}

//creating instance block
{
System.out.println("instance block 2 is executed");
}

public static void main(String[] args) {
BlocksDemo object1 = new BlocksDemo();
System.out.println("-----After creating another object---------------");
BlocksDemo object2 = new BlocksDemo();
}
}
output:
static block 1 is executed
static block 2 is executed
instance block 1 is executed
instance block 2 is executed
Constructor is executed
Instance block in Constructor is executed
-----After creating another object---------------
instance block 1 is executed
instance block 2 is executed
Constructor is executed
Instance block in Constructor is executed


Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.