Java: Static Initialization blocks v/s Instance Initialization blocks

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

Let us detail out difference between Static Initialization blocks v/s Instance Initialization blocks in tabular form below,

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

 

References:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.6

 

Read Also:

Happy Coding !!
Happy Learning !!