Monday, November 5, 2012

Static Data Area in JVM


A demonstration:
public class StaticDemo {

 // a static initialization block, executed once when the class is loaded
 static {
  System.out.println("Class StaticDemo loading...");
 }

 // a constant
 static final long ONE_DAY_IN_MILLIS = 24 * 60 * 60 * 1000;

 // a static field
 static int instanceCounter;

 // a second static initialization block
 // static members are processed in the order they appear in the class
 static {
  // we can now acces the static fields initialized above
  System.out.println("ONE_DAY_IN_MILLIS=" + ONE_DAY_IN_MILLIS
    + " instanceCounter=" + instanceCounter);
 }

 // an instance initialization block
 // instance blocks are executed each time a class instance is created
 {
  StaticDemo.instanceCounter++;
  System.out.println("instanceCounter=" + instanceCounter);
 }

 public static void main(String[] args) {
  System.out.println("Starting StaticDemo");
  new StaticDemo();
  new StaticDemo();
  new StaticDemo();
 }

 static {
  System.out.println("Class StaticDemo loaded");
 }

}
Output:
Class StaticDemo loading...
ONE_DAY_IN_MILLIS=86400000 instanceCounter=0
Class StaticDemo loaded
Starting StaticDemo
instanceCounter=1
instanceCounter=2
instanceCounter=3
Notice how 'Starting StaticDemo' does not appear as the first line of output. This is because the class must be loaded before the main method can be executed, which means all static fields and blocks are processed in order.
If there is no these code:
  new StaticDemo();
  new StaticDemo();
  new StaticDemo();

The output would be:
Class StaticDemo loading...
ONE_DAY_IN_MILLIS=86400000 instanceCounter=0
Class StaticDemo loaded
Starting StaticDemo

Which means method/block/variable are loaded in even there is not instance of this class during runtime.
` after class being loaded, those static data would be stored in "static data"
Heap and stack - what is it?
` Class will be loaded at runtime and only when this .class is running.

No comments:

Post a Comment