Monday, August 29, 2016

Static Blocks in Java

Static blocks are also called Static initialization blocks. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example: 
static {
    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And don’t forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes. Here are a couple of points I like to mention: 

  • If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.
  • If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.
So what are the advantages of static blocks?
  • If you’re loading drivers and other items into the namespace. For ex, Class has a static block where it registers the natives.
  • If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded.
  • Security related issues or logging related tasks

Of course there are limitations for static blocks 

  • There is a limitation of JVM that a static initializer block should not exceed 64K.
  • You cannot throw Checked Exceptions.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.

No comments:

Post a Comment