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 | for (type var : array) |
You can interpret the above code as:
1 | for (int i=0; i<arr.length; i++) |
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:
Use JAD to decompile java files
Now we have a ForEachDemo.java:
1 | public class ForEachDemo { |
We can use javac
command to compile ForEachDemo.java
, then use jad
command to decompile the produced class file:
After decompilation, JAD creates a ForEachDemo.jad
for us:
We can open it in a text editor:
1 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. |
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 | for (int num : marks) |