Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using a variable before it has been initialised

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • 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
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • 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
 
Sebanti Sanyal
Ranch Hand
Posts: 58
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • 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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic