Browse a Java table with the for each loop
The for each loop is a popular feature introduced with the Java SE platform in version 5.0. Its structure allows you to simplify the code by visiting each array element without specifying its size. The for each loop is used when we have a generic declaration of an array of type String, integer, etc.
for (int i=0; i < array.length; i++) {
System.out.println("Element: " + array[i]);
}
this loop is equivalent to:
for (String element: array) {
System.out.println("Element: " + element);
}
Example:
Runtime:public class JavaForEachOverArray {
public static void main(String args[]) {
String[] languages_prog = {"Java", "C", "C++", "PHP", "JavaScript"};
// loop with the for each
System.out.println("Browse the array using the Java 1.5 foreach loop");
for(String str: languages_prog){
System.out.println(str);
}
// browse with the classic loop
System.out.println("Browse the array using the for loop");
for(int i=1; i <= languages_prog.length; i++)
system.out.println(languages_prog[i]);
}
}
Browse the array using the Java 1.5 foreach loop
Java
C
C++
PHP
JavaScript
Browse the array using the for
Java
C
C++
PHP
JavaScript
Resources: