• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

static block weird case

 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is a weird case in static block initialization with a static variable. It seems you can put the static block before the declaration, since the following code works! but why?



To make things more weird, the following code won't work! You can't refer the static variable. Error message: "illegal forward reference". Why?

 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is explained in the JLS here. Basically, you can use a variable in an initializer block before it's declared in only one way: as the left-hand-side of an assignment statement.
 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much. It is really tricky.
 
blacksmith
Posts: 1332
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ernest, any idea why that restriction exists? Seems like it shouldn't be so difficult for the compiler to figure out....
 
Ernest Friedman-Hill
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's nominally to prevent cycles in initializers. If this restriction didn't exist, then



would be legal. It's illegal only because "j" is used somewhere besides on the left-hand-side of an assignment in the static block.
 
Ranch Hand
Posts: 374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Even more confusing to many is this case:


Running a program and accessing i reveals that i is zero!

Initializers are executed in the order present in the source file, effectively resulting in the block

 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic