Strange for-each loop java

  • A+
Category:Languages

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?

 


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, length = ints.length; index < length; index++) {     int i = ints[index];     System.out.println(i);     i = 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: