That one does not compile. The test defined
outside the for-loop's brackets has a scope that covers
the one inside the loop brackets and therefore is a
duplicate definition. If the variables in your example are
class-vrliables ans your loop is inside a method, then
the its ok.
this fails to compile:
Code:
int b=4; // definition scope covers form here to the end of the method that contains the loop
.
.
for (int i=0;i<5;i++) {
int b=7; // double definition
}
this is ok:
Code:
for (int i=0;i<5;i++) {
int b=7; // definition scope is from here to the first right-bracket
}
int b=4; // this has no 'backwards' scope
Check out the java rules on variables' definition scope.
Bookmarks