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:
4. Print the values of instance variables 'a' and 'b' in main( ) method as shown below:
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.
'final' instance variables will be explained in the next post.
3 comments:
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.
@ Rajiv Gandhi - Updated. Thanks.
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.
Post a Comment