VOOZH about

URL: https://www.geeksforgeeks.org/java/using-instance-blocks-in-java/

⇱ Using Instance Blocks in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Using Instance Blocks in Java

Last Updated : 22 Jan, 2026

An instance block (also called an instance initialization block) is a nameless block of code defined inside a class. It executes every time an object of the class is created, before the constructor is executed.

  • Declared inside a class but outside all methods
  • Executed once per object creation
  • Common logic shared across all constructors
  • Executed before the constructor
  • Cannot accept parameters

Syntax

class ClassName {

{

// Instance block code

}

}

Example 1: Instance Block with Multiple Constructors


Output
Instance block
1st argument constructor
Instance block
2nd argument constructor
Instance block
3rd arguments constructor

Explanation:

  • The instance block executes before every constructor call.
  • Regardless of which constructor is used, the instance block runs first.
  • This ensures shared logic executes uniformly for all object types.

Note: The sequence of execution of instance blocks follows the order- Static block, Instance block, and Constructor.

Example 2: Demonstrating Execution Order


Output
I am Static block!
I am Instance block!
I am Constructor!

Explanation:

  • Static block executes once when the class is loaded.
  • Instance block executes each time an object is created.
  • Constructor executes last to complete object initialization.

Why Use Instance Blocks?

Advantages

  • Avoids code duplication across multiple constructors
  • Ensures common initialization logic runs for every object
  • Useful when multiple constructors require the same setup logic

Limitations

  • Cannot accept parameters
  • Not suitable for object-specific initialization
  • All objects are initialized with the same logic and values

When to Use Instance Blocks

  • When common logic must run for all constructors.
  • When initialization does not depend on constructor parameters.
  • When code reuse across constructors is required.

When to Avoid Instance Blocks

  • When initialization requires parameters
  • When constructor-specific logic is sufficient
  • When readability may be affected due to hidden execution flow
Comment
Article Tags:
Article Tags: