Java Examples - Using for and foreach Loops

Java 实例Java Examples

The for statement is relatively simple and is used for looping through data.

The number of times the for loop executes is determined before execution. The syntax is as follows:

for(初始化; 布尔表达式; 更新) {
    //代码语句
}

The foreach statement is one of the new features of Java 5. It provides great convenience for developers in traversing arrays and collections.

The foreach syntax is as follows:

for(元素类型t 元素变量x : 遍历对象obj){ 
     引用了x的java语句; 
} 

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 a for loop to iterate an 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 a foreach loop to iterate an array"); for (int a : data) { System.out.print(a+ " "); } } }

The output of the above code is:

使用 for 循环数组
1 2 3 4 
使用 foreach 循环数组
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 loop For-Each for(int element:arr) { System.out.println(element); } System.out.println("---------For-Each loop over a two-dimensional array-------------"); //Traversing a two-dimensional array int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ; for(int[] row : arr2) { for(int element : row) { System.out.println(element); } } //Three ways to traverse a List collection List<String> list = new ArrayList<String>(); list.add("Google"); list.add("Example"); list.add("Taobao"); System.out.println("----------Method 1: Ordinary for loop-----------"); for(int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } System.out.println("----------Method 2: Using an 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 output of the above code is:

----------使用 for 循环------------
1
2
3
4
5
---------使用 For-Each 循环-------------
1
2
3
4
5
---------For-Each 循环二维数组-------------
1
2
3
4
5
6
7
8
9
----------方式1:普通for循环-----------
Google
Example
Taobao
----------方式2:使用迭代器-----------
Google
Example
Taobao
----------方式3:For-Each 循环-----------
Google
Example
Taobao

Java 实例Java Examples

Other extensions