The usual form the of for each loop is this:
for(Foo bar: bars){
bar.doThings();
}
But if I want to retain bar until after the loop, I can not use the for each loop:
Foo bar = null;
// - Syntax error on token "bar", Identifier expected after this token
for(bar: bars){
if(bar.condition())
break;
}
bar.doThings();
The for loop gets the syntax error mentioned above.
Why is this?
I’m not interested in workarounds, but just curious to the considerations behind this limitation.
In contrast, with an ordinary for loop, the variable can be declared outside or not at all…
int i = 1;
for(;i<max;i++){
for(;;){
// Do things
}
}
This is a good question and I would be happy to see some in-depth answer. However, the official documentation says:
The great majority of cases is the answer for me.
On a side note, personally, I think that
foreachloop in Java is just a nice syntax for a standard iterator loop. So, the compiler creates the iterator for the structure and uses the variable to get the value for current iteration. To ensure that the variable has been initialised you need to declare it for the scope of loop (and I think this prevents the variable from being used somewhere else, e.g. in another thread). Because of that, you cannot use the variable after the loop. But, this is just my opinion and I would be very happy to hear from someone who knows it better. 🙂Edit Here is an interesting article about
foreachloops in Java.Another edit I analysed (with jclasslib the bytecode of these methods:
Both methods are represented by the same bytecode:
The difference is in line 1, the latter method uses
invokevirtual #8. However, both invocations result in calling the same method ofIterator. So, it seems thatforeachis nothing more than a syntactic sugar that the compiler just translates into a predefined construct, just as the documentation says. This does not answer the question why it is the way it is. I though this is just interesting and might be worth to know, in the context of the discussion.