Now lets have some useful stuffs regarding initialization block. It is just a block defined as the static. We can have print statement ,  static method call but we cannot declare any static variable in static initialization block. When any class is loaded then first JVM will initialize the static variable and then execution starts and initialization block statements are first  to be executed by the JVM even before executing main ( ) .

Syntax of static initialization block :
< static > {  } 

 Let me make you clear with the help of an example.

public class prog4 {

static int i ;

static {

System.out.println("Static initialization Block");

}

public static void main(String sush[]) {

System.out.println(i);

    }

}

In the above example we can see that after declaring static variable a static block is defined and then main method.

Steps for the execution of the above program : 


1 >Here first JVM will load the .class file and while loading it will first initialize the static variable. By default its value is zero.

2> After initializing static variable it will start execution and first it will execute the all the static block defined in the program.

3> After executing it will execute the main method. But if there is any function call in the static block then the control will be transferred to the static method. 

Like if we want to store the return value from a method to the static variable then it will first execute the method then assign the value to the static variable and then the execution will start with the static block if any.
For ex-

public class prog4 {

static int i=value() ;

static int value (){
return 2 ;

static {
System.out.println("Static initialization Block");
}
public static void main(String sush[]) {

System.out.println(i);
    }
}

Steps of execution for the above program :

1 >First JVM will call the value() and then assign 2 to the static variable " i ". 

2> After assigning value to the variable it will execute the static block and print the " initialization block ".

3> Then execute the main () and print the value of i as " 10 " .

Note : If we have multiple static block then execution will follow the order of declaration of static block . Execution will be top to bottom from the class declaration . And if any sub class extending super class then all super class static block will be executed first then all sub-class static block. 

1 comment:

Blog Archive

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic