Sunday, 15 July 2012

Java Static Blocks – Static Initialization


Generally, a Java programmer initializes variables in a constructor (or init() method in case of applet). It is the best place chosen, as the constructor is called implicitly when an object is created. Programmer creates objects before anything is done in coding (as object is required to call an instance variable or method).

In the place of a constructor, a static block can be chosen, if the programmer does not like to have a constructor. One more advantage is static block is executed even before main() method is executed. That is, Java execution starts from static blocks and not from main() method.

Three programs are given on static blocks; each differ slightly.

In the following program, the instance variables are static. As they are static, they called from main() without the help of an object.


public class Demo
{
   double $rate;
   int numOfDollars;
   static Demo d1;
   static
   {
        d1 = new Demo();
        d1.$rate = 44.6;
        d1.numOfDollars = 12;
        System.out.println("I am static block, I am called first.");
   }
   public static void main(String args[])
   {
        System.out.println("I am main() method, executed after static block.");
        System.out.println("Dollar value in Rupees: " + d1.$rate * d1.numOfDollars);
   }
}




After executing static block, main() is executed. Observe the screenshot.

The previous program can be modified where instance variables are not static. Then you require an object to call them from static main() method.



public class Demo
{
   double $rate;
   int numOfDollars;
   static Demo d1;
   static
   {
        d1 = new Demo();
        d1.$rate = 44.6;
        d1.numOfDollars = 12;
        System.out.println("I am static block, I am called first.");
   }
   public static void main(String args[])
   {
        System.out.println("I am main() method, executed after static block.");
        System.out.println("Dollar value in Rupees: " + d1.$rate * d1.numOfDollars);
   }
}



Multi Static Blocks

A program can have any number of static blocks.


public class MultiStaticBlocks
{
    static
    {
        System.out.println();
        System.out.println("From first static block.");
    }
    static
    {
        System.out.println("From second static block.");
    }
    static
    {
        System.out.println("From third static block.");
    }
}




Observe, purposefully, the main() method is not included in the program. Even then, the program compiles and runs as static blocks are called before main(). Look at the screenshot, the main() is checked by the JVM after calling all static blocks. As the main() is not available, an exception is thrown.





No comments:

Post a Comment

There was an error in this gadget