As many of other answers correctly state, the for
each
loop
is just syntactic sugar over the same old for
loop
.
You can see the actual for loop to which it is translated by using the -XD-printflat
switch for javac (open jdk).
javac -XD-printflat -d src/ MyFile.java
-d is used to specify the directory for output java file
When you use this switch the compiler
generates a new java
file with all the syntactic sugar removed.(ie for each converted to same old for loop)
Lets remove the syntactical sugar
To answer this question, I created a file and wrote two version of for
each
, one with array
and another with a list
. my java
file looked like this.
import java.util.*;
public class Temp{
private static void forEachArray(){
int[] arr = new int[]{1,2,3,4,5};
for(int i: arr){
System.out.print(i);
}
}
private static void forEachList(){
List<Integer> list = Arrays.asList(1,2,3,4,5);
for(Integer i: list){
System.out.print(i);
}
}
}
When I compiled
this file with above switch, I got the following output.
import java.util.*;
public class Temp {
public Temp() {
super();
}
private static void forEachArray() {
int[] arr = new int[]{1, 2, 3, 4, 5};
for (/*synthetic*/ int[] arr$ = arr, len$ = arr$.length, i$ = 0; i$ < len$; ++i$) {
int i = arr$[i$];
{
System.out.print(i);
}
}
}
private static void forEachList() {
List list = Arrays.asList(new Integer[]{Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(5)});
for (/*synthetic*/ Iterator i$ = list.iterator(); i$.hasNext(); ) {
Integer i = (Integer)i$.next();
{
System.out.print(i);
}
}
}
}
You can see that with other syntactic sugar (Autoboxing) for each loops got changed to simple loops.