For-each in Java

For-each in Java

Introdcution

For-each is an array traversing technique in Java, which is an enhancement to for-loop. The syntax of for-each loop is as follows:

1
2
3
4
for (type var : array) 
{
statements using var;
}

You can interpret the above code as:

1
2
3
4
5
for (int i=0; i<arr.length; i++) 
{
type var = arr[i];
statements using var;
}

But is the interpretation true? Now we are going to use JAD Java Decompiler to prove it.

Install JAD on Mac

We can use homebrew to install JAD:

brew cask jad

And brew will download and install JAD for you. Then you can use jad command to verify JAD has been installed:

jad

Use JAD to decompile java files

Now we have a ForEachDemo.java:

1
2
3
4
5
6
7
8
9
10
public class ForEachDemo {

public static void main(String[] args) {
int[] array = {1,2,3,4,5};
for (int element: array) {
System.out.println(element);

}
}
}

We can use javac command to compile ForEachDemo.java, then use jad command to decompile the produced class file:

decompile_for_each_demo

After decompilation, JAD creates a ForEachDemo.jad for us:

jad_file

We can open it in a text editor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: ForEachDemo.java

import java.io.PrintStream;

public class ForEachDemo
{

public ForEachDemo()
{
}

public static void main(String args[])
{
int ai[] = {
1, 2, 3, 4, 5
};
int ai1[] = ai;
int i = ai1.length;
for(int j = 0; j < i; j++)
{
int k = ai1[j];
System.out.println(k);
}

}
}

From the decompiled code, we can verify our previous interpretation.

Limitation of For-each loop

From the above conclusion, we can know that for-each loops are not appropriate when you want to modify the array:

1
2
3
4
5
for (int num : marks) 
{
// only changes num, not the array element
num = num*2;
}