top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Java: what is importance of Static & instance block?

+2 votes
624 views
Java: what is importance of Static & instance block?
posted Mar 1, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM.

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 dont 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.

Advantages of static blocks:

  • If you’re loading drivers and other items into the namespace. For ex, Class 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

Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
For more about it : http://www.javatpoint.com/instance-initializer-block

answer Mar 1, 2015 by Amit Kumar Pandey
...