Strange for-each loop java

alqueen :

Could anyone tell me, why does it works?

int[] ints = {1,2,3};
for(int i : ints) {
System.out.println(i); i = 0;
}

Why can I set 0 as i, but it still iterates?

T.J. Crowder :

Because i isn't a control variable in that loop, it's just one of the values in the array. Per JLS§14.4.2, for arrays, the enhanced for loop is equivalent to this:

The enhanced for statement is equivalent to a basic for statement of the form:

...

for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

So applying that to your loop:

int[] ints = {1,2,3};
for (int index = 0; index < ints.length; index++) {
    int i = ints[index];
    System.out.println(i);
    i = 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84477&siteId=1