Instance Block and Static Blocks in Java

 

Instance Block and Static Block

 

In Java, there are two types of blocks that can be used within a class: instance blocks (also known as instance initializer blocks) and static blocks (also known as static initializer blocks).

  1. Instance Blocks: Instance blocks are used to initialize instance variables of a class. They are executed whenever an instance of the class is created, before the constructor is invoked. An instance block is defined within a class without any keywords or modifiers.

Here’s an example:

public class MyClass {
private int value;

// Instance block
{
// Initialization code
value = 10;
System.out.println(“Instance block executed”);
}

// Constructor
public MyClass() {
// Constructor code
System.out.println(“Constructor executed”);
}
}

 

In the above example, the instance block initializes the value variable with a value of 10. It is executed before the constructor when an object of MyClass is created.

  1. Static Blocks: Static blocks are used to initialize static variables of a class or perform some static initialization tasks. They are executed only once when the class is loaded into memory, before any objects of the class are created. A static block is defined with the static keyword.

 

Here’s an example:

public class MyClass {
private static int count;

// Static block
static {
// Initialization code
count = 0;
System.out.println(“Static block executed”);
}

// Constructor
public MyClass() {
// Constructor code
count++;
System.out.println(“Constructor executed”);
}
}

Related Posts