This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

local variables--confusing me

 
Danish Shaukat
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi folks !

If i am not wrong, then local variables are not initialized automatically when they are declared.If this rule is violated compiler gives an error.
But i have two small snippets of code.
In one code snippet the above stated rule holds true.
In the othe one it is violated as the code does compile.
Why ?

Class Zoo57 gives an error.
public class Zoo57
{
public static void main(String[] args)
{
int x=1,total;
while(x<=10)
{

total+=x;
++x;
}
System.out.println("total is..."+total);
}

}
////////////////////////////////////////
Class Zoo56 does not give an error.
public class Zoo56
{
public static void main(String[] args)
{
int y,x=1,total=0;
while(x<=10)
{
y=x*x;
System.out.println(y);
total+=x;
++x;
}
System.out.println("total is..."+total);
}

}
--Danish
[ October 24, 2002: Message edited by: Danish Shaukat ]
 
arun mahajan
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is in First case:
You are trying to add into total where total is not intialized and compiler is complaing for it.
But in other case you are though you haven't intialize it first but in other line you are simply assigning the value by saying:
y=x*x;
and the reason compiler this time not complaining.
Hope it will help.
Arun
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic