alqueen
alqueen

Reputation: 233

Strange for-each loop java

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?

Upvotes: 2

Views: 195

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074919

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;
}

Upvotes: 7

optional
optional

Reputation: 3350

for( int i : ints ) 

is called enhanced for loop . When you deal iterable like this , you deal with element in iterable rather then index .

You can read this

for each element i { // do this ; }

In your case i is not index , it is current element in iterable.

iterable is not instance of Iterable here . It is in generic sense that any collection that can be iterated using like this.

Upvotes: 1

Eran
Eran

Reputation: 393916

i is not the loop's index in this case, it's the value of the current element of the array. Therefore changing it doesn't affect the iteration.

It is equivalent to:

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

Upvotes: 4

Related Questions