Saturday, September 29, 2012

Static Block

If you need to do computation in order to initialize your static variable, you can declare a static block which gets executed exactly once, when the class is first loaded.

Following example shows a class that has static method, some static variable and static initialization,

class useStatic {
  static int a=3;
  static int b;

  static void sMethod(int x){
    System.out.println ("x = "+x);
    System.out.println ("a = "+a);
    System.out.println ("b = "+b);
  }

  static {
     System.out.println (" static block initialized");
     b = a * 4;
  }

  public static void main(String arg[]){
   sMethod(42);
  }

As soon as the useStatic class is loaded, all the static statement are executed. First a is set to 3, then the static block executes (printing a message), and finally b is initalized to a*4 or 12. The main is call,  which calls sMethod() , passing 42 to x so the output is x= 42,a = 3, b = 12.  

the o/p is look's like :

static block initialized
x = 42
a = 3
b = 12

Hope this example helps you to understand static .....

No comments:

Post a Comment