java blocks tutorial

Bodhak java blocks tutorial with blocks in this chapter we will discuss in detail about Working with blocks,      Nonstatic block, Static block, what is need of static and nonstatic block.

Working with blocks : An initialization block is a block of code between braces that is executed before the object of the class is created



java blocks tutorial

They are 2 types:

  1. Static initialization block.
  2. Nonstatic initialization block.


Static initialization block

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword and is executed once when the class is loaded.

is used to initialize the static data member.

It is executed before the main method at the time of class loading.

A class can have any number of static initialization blocks, and they can appear anywhere in the class body.

Nonstatic initialization block:

It is dependent on the object and the initialization block is executed for each object of the class that is created. It can initialize instance member variables of the class

Initializing Instance Members:

To initialize code to an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initialize blocks and final methods.

Initializing blocks for instance variables look just like static initializing blocks, but without the static keyword


// whatever code is needed for initialization goes here


The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors