wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static block & static var 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 block & static var" Watch "static block & static var" New topic
Author

static block & static var

Jonathan Jeban
Ranch Hand

Joined: Oct 08, 2000
Posts: 52
Hi,


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

TIA,
Jeban.
Peter Tran
Bartender

Joined: Jan 02, 2001
Posts: 783
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

Joined: Dec 29, 2000
Posts: 37
Good explanation Peter. Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static block & static var
 
Similar Threads
Help Creating Class
GREAT ANOMOly and border layout?
Mock Question problem
please explain why the compiler is not complaining and why the output is 0
A question about "Increment"