This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach 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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 1167
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).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Using a variable before it has been initialised
 
Similar Threads
Member inner class
initialization and if
LOCAL VARIABLE
this(a)
compile time constants