'static' block

If you need computation in order to initialize your static variables, you can declare a static block that gets executed before the main( ) is called.

Lets implement this on Eclipse IDE:

1. Create a class 'StaticBlockDemo' under any project as shown below:



2. Declare instance variables 'a' and 'b' of int type and specify them as 'static' as shown below (Initialize only 'a' instance variables for now) :



3. Create 'static' block to perform some computations on instance variable 'a' and assign the result to instance variable 'b' as shown below:


4. Print the values of instance variables 'a' and 'b' in main( ) method as shown below:



5. Save and Run the 'StaticBlockDemo' class as shown below:


6. Observe that output is displayed as shown below:



After looking at output, its very clear that this class is executed in the following way:

1. All the statements are executed first :
  • First, static int a = 5 is executed first  (i.e. value of a is assigned a value 5 first)
  • Second, all the statements in the 'static' block are executed 
2. Later main( ) method is executed, so the output.