Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Declaration

 
Saket Barve
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody explain how the variable i can be declared twice in the following error-free code?
The output is 100. Now I don't understand what happens to the integer i assigned the value of 10 in the static block.
I'd appreciate any feedback at the earliest.
Thanks,
Saket
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The i declared within the static initializer block is "shadowing" the static member varaible of the same name. In short, that means that, within that block, any references to a variable named i will refer to the local variable, not the member variable. Also, as the new variable i is local, it goes out of scope as soon as the static initializer block completes. Therefore, when main is executed, there is only one variable named i - the member variable. The other once has already gone out of scope.
You can find more information about shadowing declarations in the JLS, §6.3.1 Shadowing Declarations.
I hope that helps,
Corey
[ May 06, 2003: Message edited by: Corey McGlone ]
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Corey, crystal clear, as always.
 
Saket Barve
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Corey, I get it now.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic