Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static block & static var

 
Jonathan Jeban
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


Can anyone explain why the program doesn't throws error for i
re-declaration???

TIA,
Jeban.
 
Peter Tran
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jonathan,
You almost got me with your question. This is my answer.
With the static block using the static { } idiom, you're actually creating block of code that will be evaluated when the class is loaded. Here's the catch, all variable declared inside this block is local to that block only. It doesn't exist anymore outside the block. So the compiler won't flag it as an error.
If you modified your code to set the variable i to 40 inside the block, the program still prints 10. This is because while you're inside the block, the local variable i shadows the outer static int i variable.

This output will give you 40, 10.

Now if you modify your code so it doesn't declare a new int i variable, then you will modify the original outer static int i.

The second output will give you 40, 40.
-Peter
 
Rakesh Sharma
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good explanation Peter. Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic