Saturday, 21 July 2018

SE - 26 - Static Block

Static Block is used for static initialisation of class.

i) The code written in static block runs only once whenever a object of class is created for the first time .

ii) The code written in static class can even execute when we call a static variable of that class but it will be called only once.

iii) There can be multiple static blocks in a class. They will run in the sequence its defined. All of them will run only once in either of above two conditions.

class Test{
   static int num;
   static{
      System.out.println("Static Block  : 1");
  } 

  static{
      System.out.println("Static Block :  2");
  }


iv) If there are multiple static block with the different value of the static variable then the value will be overrided and the last value will be set. (Since the static members are shared across the project)

v) If we miss to write the word static while defining static block then the piece of code will be considered as constructor block and will be called.

vi) Super , this keywords are not supported in static block and checked exceptions are also not allowed



No comments:

Post a Comment