aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using a variable before it has been initialised 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 "Using a variable before it has been initialised" Watch "Using a variable before it has been initialised" New topic
Author

Using a variable before it has been initialised

O. Ziggy
Ranch Hand

Joined: Oct 02, 2005
Posts: 430



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

Joined: Jul 09, 2001
Posts: 1174
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


William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
Sebanti Sanyal
Ranch Hand

Joined: Nov 07, 2011
Posts: 58

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).
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Using a variable before it has been initialised