File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

static block & static var

Jonathan Jeban
Ranch Hand

Joined: Oct 08, 2000
Posts: 52

Can anyone explain why the program doesn't throws error for i

Peter Tran

Joined: Jan 02, 2001
Posts: 783
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.
Rakesh Sharma
Ranch Hand

Joined: Dec 29, 2000
Posts: 37
Good explanation Peter. Thanks.
I agree. Here's the link:
subject: static block & static var
It's not a secret anymore!