Java Examples - Using for and foreach Loops
The for statement is straightforward and used for looping through data.
The number of times a for loop executes is determined before execution. The syntax is as follows:
for(initialization; boolean expression; update) {
// Code statements
}
The foreach statement is one of the new features in Java 5, providing significant convenience for developers when iterating over arrays and collections.
The foreach syntax is as follows:
for(element type t element variable x : iterable object obj) {
Java statement referencing x;
}
The following example demonstrates the use of for and foreach loops:
Main.java File
public class Main {
public static void main(String[] args) {
int[] intary = { 1, 2, 3, 4 };
forDisplay(intary);
foreachDisplay(intary);
}
public static void forDisplay(int[] a) {
System.out.println("Using for loop to iterate over the array");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void foreachDisplay(int[] data) {
System.out.println("Using foreach loop to iterate over the array");
for (int a : data) {
System.out.print(a + " ");
}
}
}
The output of the above code is:
Using for loop to iterate over the array
1 2 3 4
Using foreach loop to iterate over the array
1 2 3 4
Main.java File
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println("----------Using for Loop------------");
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println("---------Using For-Each Loop-------------");
// Enhanced for-each loop
for(int element : arr) {
System.out.println(element);
}
System.out.println("---------For-Each Loop for 2D Array-------------");
// Iterating over a 2D array
int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for(int[] row : arr2) {
for(int element : row) {
System.out.println(element);
}
}
// Traversing a List in three ways
List<String> list = new ArrayList<String>();
list.add("Google");
list.add("tutorialpro");
list.add("Taobao");
System.out.println("----------Method 1: Regular for loop-----------");
for(int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
System.out.println("----------Method 2: Using Iterator-----------");
for(Iterator<String> iter = list.iterator(); iter.hasNext();)
{
System.out.println(iter.next());
}
System.out.println("----------Method 3: For-Each Loop-----------");
for(String str: list)
{
System.out.println(str);
}
The above code outputs:
----------Using for loop------------
1
2
3
4
5
---------Using For-Each loop-------------
1
2
3
4
5
---------For-Each loop for 2D array-------------
1
2
3
4
5
6
7
8
9
----------Method 1: Regular for loop-----------
Google
tutorialpro
Taobao
----------Method 2: Using Iterator-----------
Google
tutorialpro
Taobao
----------Method 3: For-Each Loop-----------
Google
tutorialpro
Taobao