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.

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.