for循环提供了编写循环结构的简洁方法。与while循环不同,for语句消耗了一行中的初始化,条件和递增/递减,从而提供了一个更短,更易于调试的循环结构。
句法:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
} 流程图:

// Java program to illustrate for loop.
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}
输出:
Value of x:2 Value of x:3 Value of x:4
Java还包括在Java 5中引入的另一个版本的for循环。Enhanced for循环提供了一种更简单的方式来遍历集合或数组的元素。它是不灵活的,只有在需要以顺序方式迭代元素而不知道当前处理元素的索引时才应该使用它。
句法:
for (T element:Collection obj/array)
{
statement(s)
} 让我们举一个例子来演示如何使用增强的循环来简化工作。假设有一个名称数组,我们希望打印该数组中的所有名称。让我们看看这两个示例的不同之处
Enhanced for循环简化了以下工作:
// Java program to illustrate enhanced for loop
public class enhancedforloop
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};
//enhanced for loop
for (String x:array)
{
System.out.println(x);
}
/* for loop for same function
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}
输出:
Ron Harry Hermoine
基本for循环的一些常见误区,可以参照:在Java中的For循环