Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes local variables--confusing me 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 » Java » Beginning Java
Bookmark "local variables--confusing me" Watch "local variables--confusing me" New topic
Author

local variables--confusing me

Danish Shaukat
Ranch Hand

Joined: Nov 16, 1999
Posts: 340
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

Joined: Dec 07, 2001
Posts: 305
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
 
Don't get me started about those stupid light bulbs.
 
subject: local variables--confusing me
 
Similar Threads
ques
Correct output for this program?
properly initialized
java data types initializing
Method Variable