How to use Static Blocks and Instance Initializers in Java


Examine the following code to understand how Static Blocks and Instance Initializers work in Java Environment

package staticblocksstaticinitializerexample;

/**
 *
 * @author tunatore
 */

//SYNTAX
// public class CLASS{
//
//    static{
//    ….
//    }
//    {
//    …
//    }
//    //variables
//    //methods
//}

public class AnObject {

/**
     * static blocks and static initializer example
     */

static int value;

//runs only once when the class first loaded by Java JVM
    //static block
static {    
value = 100;
System.out.println(Called by JVM only once! value is –> + value);
}

//this Instance Initializer runs every time when a new instance created

value++;
System.out.println(“Every time runs when a new instance is created!”);
}
public static void main(String[] args) {

{
  //this is not an Instance Initializer
            //this block runs only once as a regular statement
System.out.println(“This is not an Instance Initializer”);

}

AnObject object = new AnObject();
System.out.println(“value is –> “ + object.value);

AnObject object2 = new AnObject();
System.out.println(“value is –> “ + object2.value);

AnObject object3 = new AnObject();
System.out.println(“value is –> “ + object3.value);

}

}

Output of the program

run:
Called by JVM only once! value is –> 100
This is not an Instance Initializer
Every time runs when a new instance is created!
value is –> 101
Every time runs when a new instance is created!
value is –> 102
Every time runs when a new instance is created!
value is –> 103
BUILD SUCCESSFUL (total time: 1 second)

Download Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s