It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Declaration" Watch "Static Declaration" New topic

Static Declaration

Saket Barve
Ranch Hand

Joined: Dec 19, 2002
Posts: 229
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.
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,
[ 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: 229
Thanks Corey, I get it now.
I agree. Here's the link:
subject: Static Declaration
It's not a secret anymore!