| Author |
Static Declaration
|
Saket Barve
Ranch Hand
Joined: Dec 19, 2002
Posts: 224
|
|
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
Joined: Dec 20, 2001
Posts: 3271
|
|
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 ]
|
SCJP Tipline, etc.
|
 |
Marlene Miller
Ranch Hand
Joined: Mar 05, 2003
Posts: 1391
|
|
|
Corey, crystal clear, as always.
|
 |
Saket Barve
Ranch Hand
Joined: Dec 19, 2002
Posts: 224
|
|
|
Thanks Corey, I get it now.
|
 |
 |
|
|
subject: Static Declaration
|
|
|