Take it like that. If you were allowed to declare the variable i in the for loop, then how would you refer to the local variable i declared before the for loop? You cannot do this with any qualified name, and a simple name will refer to a loop loop variable. That is why it is forbidden.
The behavior is given in JLS. From JLS - section 6.4 :
A local variable (§14.4), a formal parameter (§8.4.1), an exception parameter (§14.20), and a local class (§14.3) can only refer to a simple name (§6.2), not a qualified name (§6.6).
Some declarations are not allowed within a local variable, formal parameter, exception parameter, or local class declaration, since it would be impossible to distinguish declared objects using only simple names .
And from JLS - Section 6.3 :
The declaration volume of a local variable in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any subsequent declarators to the right of the declaration of the local variable.
The emphasis is mine.
Again, section 6.4 of the JLS section states that re-declaring a local variable in the same scope will result in a compile-time error:
This is a compile-time error if the name of the local variable v is updated as a local variable of a directly nested method, constructor or initialization block within the scope of v; or as an exception parameter in a catch clause in a try statement of a directly related method, constructor or initializer block within scope v; or as a resource in a try-with-resources statement of a directly nested method, constructor, or initializer block within scope v.
source share