Google+

90. '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.

Download this project:

Click here to download the project containing the class file used in this post (You can download the project and import  into Eclipse IDE on your machine)





Please comment below to feedback or ask questions.

'final' instance variables will be explained in the next post.


3 comments:

rajiv gandhi said...

First, static int a = 3 is executed first (i.e. value of a is assigned a value 3 first)

I guess static int a=5 instead of static int a=3.

Arun Motoori said...

@ Rajiv Gandhi - Updated. Thanks.

kavitha m said...

Hi Arun,

Can I know the difference between static block and main method ,Why we need to use Main method for calling methods ,As we can use static block itself.

Followers :)

Blog Index