In this article, we will list the difference between Static Initialization blocks and Instance Initialization blocks in Java
Before moving ahead with the differences, read the detailed concepts about these cpncepts in detail in the following articles
- Initialization blocks (Static and Instance blocks)
- Execution order of constructor and Initialization blocks
Let us detail out difference between Static Initialization blocks v/s Instance Initialization blocks in tabular form below,
1. Static Initialization block v/s Instance Initialization block
Sr. No. | Static Initialization blocks | Instance Initialization blocks |
1 | This is also referred as “static blocks” or “static initializer” | This is also referred as “instance blocks” or “instance initializer” |
2 | Static blocks are bundle of valid Java statements within {curly braces} prefixed with static keyword | Instance blocks are bundle of valid Java statements within {curly braces}
Note: Just opening and closing curly braces and there is no keyword |
3 | Syntax:
static { // bundle of Java logics } | Syntax:
{ // bundle of Java logics } |
4 | Static blocks are executed, at the time of class loading | Instance blocks are executed, every time object is created using new keyword |
5 | Executed only once, at the time class loading | Executed every time instance is created |
6 | Static blocks can be used to initialize static data members and invoke static methods only | Instance blocks can be used to initialize instance data members and invoke instance methods |
7 | Since static blocks are belongs to class, this and super keywords are not allowed | this keyword are used to access instance data members in instance blocks |
8 | Order of execution: Static blocks are always executed first comparing with instance blocks, at the time class loading | Order of execution: Instance blocks are executed after static blocks, as instance blocks executed only when object created |
Read more about Initialization blocks in Java
Related Articles:
- Java Constructor with example
- Default constructor
- Parametrized constructor
- Default constructor v/s Parametrized constructor
- Constructor overloading
- Constructor chaining
- Constructor v/s Methods
- Private Constructor
- Static constructor in Java – A big interview question ?
- Constructor in Java Interface
References:
Happy Coding !!
Happy Learning !!