AddThis Social Bookmark Button

The static and non-static blocks are used as a member, in a class, both of these have their specific use in Java language. In this section we will talk about few important points about these two type of blocks

Static blocks:

  1. A static block is a block of code which contains code that executes at class loading time.
  2. A static keyword is prefixed before the start of the block.
  3. All static variables can be accessed freely
  4. Any non-static fields can only be accessed through object reference,thus only after object construction.
  5. multiple static blocks would execute in the order they are defined in the class.
  6. All static blocks executes only once per classloader
  7. A typical static block looks like
    static{
    // code for static block
    }
    
    
    

Non-static block:

  1. A non-static block executes when the object is created, before the constructor
  2. There is no keyword prefix to make a block non-static block,unlike static blocks.
  3. Incase of multiple non-static blocks , the block executes the order in which it is defined in the class.
  4. All static and non-static fields can be access freely.
  5. All non-static block executes everytime an object of the containing class is created.
  6. A typical non-static block looks like below
    {
    // non static block
    }