Why is it not possible to shadow a local variable in a loop?

I got this situation I can't understand about shadowing. For example the following code:

class Foo {
   int a = 5;
   void goFoo(int a) { 
       // No problem naming parameter as same as instance variable
       for (int a = 0; a < 5; a++) { }
       // Now the compiler complains about the variable a on the for loop
       // I thought that the loop block had its own scope so I could shadow
       // the parameter, why the compiler didn't throw an error when i named
       // the parameter same as the instance variable?
   }
}

You can make a local variable shadow an instance/static variable - but you can't make one local variable (your loop counter) shadow another local variable or parameter (your parameter).

From the Java Language Specification, section 14.4.3:

If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable.

Note the "field name" part - it's specifying that it has to be a field that is shadowed.

And from section 8.4.1:

The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor.

These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor.

(It goes on to talk about local classes and anonymous classes, but they're irrelevant in your case.)


void goFoo(int a) { 

       for (int a = 0; a < 5; a++) { }

}

it is similar to

void goFoo() { 
       int a;
       for (int a = 0; a < 5; a++) { }

}

so multiple declaration of a on the same scope, it is not acceptable.

or simply it is similar to

void goFoo() { 
  int a;
  int a;
} 

Also See

  • java-variable-scope-shadowing