Wednesday, 23 November 2016

Difference between static block and empty block in java

Static block

  1. Static block will be called when class loader is loading the class.
  2. Always static block will get execute irrespective of object creation.
  3. Only static variable can be initialized in static block. 
  4. It can used for initialization purpose when your application is starting.
  5. Instance method cannot be called from static block but you can call static method inside static block.
  6. Your application initial parameter can be initialized here, for example logger, property file and mapping file.
Example:
  static {
      // initialization of static variable
      //  only can call another static method
  }

Empty block or Object Block
  1. Empty block will be called when you are creating the object with new keyword.
  2. Empty block will not get execute if you are not creating the object.
  3. Both static and not static variable can be initialized in empty block.
  4. It will be called before your default constructor, so  preinitialization can be done here.
  5. Instance method and static method can be called form empty block.
Example:
      {
        //  initialization of static and non-static variable
        //  can call both static and non static method
      }


Java Example Program.

public class StaticClass {

static int count=0;     // static variable
 int a=0;                     //  non static variable

 static {                  // static block
   System.out.println(" staticblock ");
count++;          // initialization of  static variable
// instanceMethod();      // compile time error
     // a++;                      // compile time error
staticMethod();
}

 {         // empty block or object block
   System.out.println(" empty block ");
count++;     // valid
instanceMethod();  //valid
staticMethod();   // valid
}

StaticClass() {    // constructor
System.out.println(" default constructor");
}

public void instanceMethod() {
System.out.println(" instanceMethod");
}

public static void staticMethod() {
System.out.println(" staticMethod ");
}

public static void main(String args[]) {
System.out.println(count);
StaticClass object = new StaticClass();
System.out.println(count);
}
}

output:-

 staticblock 
 staticMethod 
1
 empty block 
 instanceMethod
 staticMethod 
 default constructor
2





If you like the above solution . Please share this blog

No comments:

Post a Comment

s