for 语句比较简单,用于循环数据。
for循环执行次数在执行之前,已经确定好了。
for(初始化;条件表达式;修改初始值表达式){
//循环体
}
foreach语句是Java5之后的新特性之一,在遍历数组、集合方面、foreach为开发人员提供极大的方便。
语法格式:
for(元素类型t 元素变量名x : 遍历对象obj){
引用x的Java语句
}
例:
public class Main {
public static void main(String[] args) {
int[] arry= { 1,2,3,4};
forTest(arry);
foreachTest(arry);
}
public static void forTest(int[] a){
System.out.println("使用 for 循环数组");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void foreachTest(int[] data){
System.out.println("使用 foreach 循环数组");
for (int a : data) {
System.out.print(a+ " ");
}
}
}
输出的结果:
使用 for 循环数组
1 2 3 4
使用 foreach 循环数组
1 2 3 4