Alex Rivera | Logout

How is Java's for loop code generated by the compiler

Asked 2010-08-08T06:08:46.860
19

How is Java's for loop code generated by the compiler?

For example, if I have:

for(String s : getStringArray() )
{
   //do something with s
}

where getStringArray() is a function that returns the Array I want to loop on, would function be called always or only once? How optimal is the code for looping using this construct in general?

Edit
Report

1 Answer

59

On the semantics of enhanced for loop

Here is the relevant excerpts from the Java Language Specification 3rd Edition, slightly edited for clarity:

JLS 14.14.2 The enhanced for statement

The enhanced for statement has the form:

for ( Type Identifier : Expression ) Statement

If the type of Expression is an array type, T[], then the meaning of the enhanced for statement is given by the following basic for statement:

T[] a = Expression;
for (int i = 0; i < a.length; i++) {
    Type Identifier = a[i];
    Statement
}

where a and i are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

So in fact the language does guarantee that Expression will only be evaluated once.

For completeness, here's the equivalence when the Expression is of type Iterable:

JLS 14.14.2 The enhanced for statement

The enhanced for statement has the form:

for ( Type Identifier : Expression ) Statement

If the type of Expression is a subtype of Iterable, then let I be the type of the expression Expression.iterator(). The enhanced for statement is equivalent to a basic for statement of the form:

for (I iter = Expression.iterator(); iter.hasNext(); ) {
    Typ
answered 2010-08-08T09:25:22.800

Your Answer