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 Scope of loop variable.... Error when compiling.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Scope of loop variable.... Error when compiling...." Watch "Scope of loop variable.... Error when compiling...." New topic
Author

Scope of loop variable.... Error when compiling....

Anoop Nair
Ranch Hand

Joined: Oct 29, 2008
Posts: 70
void function1(int x)
{
for(int x=0;x<6;x++);
}

The variable x in red color gives error: Variable with this name already exists.

The x inside the for loop has scope only within the loop. Then why does it give error when compiling???

Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
Because the x that is passed as a parameter to the method is in scope for the entire method. You can't redeclare a variable with the same name as one that is already in scope.


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Anoop Nair
Ranch Hand

Joined: Oct 29, 2008
Posts: 70
But the for loop is a separate block...

So if i declare a variable with the same name as of the enclosing block, then the variable local to the current block would take precedence...

Thats how it is supposed to work, right??

Uli Hofstoetter
Ranch Hand

Joined: Nov 24, 2006
Posts: 57
Check out the JLS, section 14.4.2, where your point is covered.


SCEA5, Certified ScrumMaster
Anoop Nair
Ranch Hand

Joined: Oct 29, 2008
Posts: 70
Thanks a lot Uli....



Adi Kulkarni
Ranch Hand

Joined: Mar 12, 2009
Posts: 86
You have declared a local variable in a method already( Say int x ). So it has a scope for that entire method.

In the for loop you are trying to redeclare the same variable again which is not allowed in this case since the variable has already been declared. You can always use that variable in the for loop eg for(x=0 ; x<smthing ; x++) .

In your case you have

method new {
int x = 0; ..................already declared
for ( int x = 0 ; x<smthing ; x++)
{}
}

So you are trying to redeclare a variable which is already in scope. No precedence is applicable in this type of declaration.

When you are having an instance variable with name "x" and a local variable with name "x" , precendence comes into play then when you are trying to access the variables with the name "x" .
In your case both are local variables and secondly you are redeclaring which is not allowed.

~Aditya


SCJP 1.5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Scope of loop variable.... Error when compiling....