• 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
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Using a variable before it has been initialised

 
Ranch Hand
Posts: 430
Android VI Editor Debian
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The above code example print "0". I think it is because the getValue() method is called before y has been initialised. I didn't realise that methods can be called before all static variables have been initialised. Is there a simple explanation for this?

Thanks
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree with you. Especially, since the following yields the expected result - 5.



Static Initialization Blocks says -

The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.



It probably applies to a sequence of static variable initialization as well (versus a static block).

Regards,
Dan
 
Ranch Hand
Posts: 58
Eclipse IDE C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Initializer expressions are executed in the order in which the fields are declared in the class. If you invoke getValue() before initializing y, it will return the default value of int(i.e. 0).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic