Tuesday 6 October 2015

Non-static initializer block

      {
            // Do something..
      }

This gets called every time the class is constructed. The static block only gets called once, no matter how many objects of that type you create.

On the other hand, static block called only once when the Object is loaded first time.



public class NonStaticBlock {
     
      static int a = 55;
     
      static {
            a = 6;
            System.out.println("static block called !!");
      }
     
      {
            a = 10;
            System.out.println("non-static block called !!");
      }
     
      public static void main(String args[]) {
            System.out.println(a);
           
            NonStaticBlock block = new NonStaticBlock();
            System.out.println(block.a);
           
            NonStaticBlock block1 = new NonStaticBlock();
      }
}
Output:
static block called !!
6
non-static block called !!
10
non-static block called !!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...