I have a pretty simple question about variable scope.
I am familiar with Enhanced For-Loops, but I do not understand why I have to declare a new variable to save each item. One example might clarify my question:
int[] ar = {1, 2, 3}; int i = 0; for(i : ar) { // this causes an error if I do not declare a new variable: int i // for(int i : ar) // this works fine System.out.println(i); }
So why should I declare this new variable? After all, i is available inside the for loop. I did not want to use the previous value of i , I just did not want to declare a new variable. (I suggested that for other repeating elements, it could be faster using the same variable).
I guess how Enhanced For-Loops were created, but doesn't that violate the idea of the whole area?
A question arises related to the above behavior. Does the compiler use the same variable for the entire for loop and just update its value or create a new variable for each iteration?
The interesting part is that if I save as an int declaration I (before and inside the for loop), I even get a compiler error
Duplicate local variable i
which makes (at least for me) things a little weirder. Therefore, I cannot use the previous declared variable i inside the for loop, but I also cannot declare a new one inside it with the same name.
java scope foreach
Eypros
source share