Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

static block & static var

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,


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

TIA,
Jeban.
 
Bartender
Posts: 783
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good explanation Peter. Thanks.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic