Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Forward referencing during variable initialization

 
Vanguard Hawk
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic