File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: local variables--confusing me
 
Similar Threads
Method Variable
java data types initializing
properly initialized
Correct output for this program?
ques