This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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?

Dan Drillich
Ranch Hand

Joined: Jul 09, 2001
Posts: 1183
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).


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).
I agree. Here's the link:
subject: Using a variable before it has been initialised
It's not a secret anymore!