This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Forward referencing during variable initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Forward referencing during variable initialization" Watch "Forward referencing during variable initialization" New topic
Author

Forward referencing during variable initialization

Vanguard Hawk
Greenhorn

Joined: Jul 28, 2011
Posts: 2
Hi,

I am working on Java 5.I am not able to understand why the below code is working fine.

Since as far as my knowledge forward referecing of varriable is not allowed during initialization while forward referencing of methods is allowed.

<Code>
class parent{

private int chairsCount = initChairsCount();

private int initChairsCount() {
tablesCount=25;
return tablesCount * 4;
}

private int tablesCount = 20;


}
</Code>

Here in the above example i am forward referencing the varriable tablesCount in the method initChairsCount().

Why the compiler is not giving me any kind of compile time error?
Sathi Krishna
Ranch Hand

Joined: Oct 21, 2007
Posts: 51

As per I know,
while compiling the variable "tablesCount" is created but value is not assigned.
If it is static variable the value will also be assigned during compile time.

So in our case, no chance for compile time error.
variable got created in memory and assigned with zero value.

Just try with commenting the below statement in your program
// tablesCount=25;

Scotty Mitchell
Ranch Hand

Joined: Aug 09, 2011
Posts: 46
Sathi Krishna wrote:As per I know,
while compiling the variable "tablesCount" is created but value is not assigned.
If it is static variable the value will also be assigned during compile time.

So in our case, no chance for compile time error.
variable got created in memory and assigned with zero value.

Just try with commenting the below statement in your program
// tablesCount=25;



If you have a debugger availiable maybe in Eclipse just run the debugger with a watch on the static variables or a breakpoint before you create a new instance of the class. You will see that upon loading an instance from the main method the variables have value = 0 before any code is stepped through. Sathi has it spot on
 
Consider Paul's rocket mass heater.
 
subject: Forward referencing during variable initialization
 
Similar Threads
Instance member Initialization.
instance variable declarations, when do they occur?
initializers-referencing
few basic questions....
about forward refrencing