for语句提供了一种紧凑的方法来迭代一系列值。程序员通常将其称为“for循环”,因为它反复循环直到满足特定条件为止。for语句的一般形式可以表示为:

    1. for (initialization; termination;
    2. increment) {
    3. statement(s)
    4. }

    使用此版本的for语句时,请记住:

    • 初始化表达式初始化回路; 当循环开始时,它执行一次。
    • 终止表达式的计算结果为时false,循环终止。
    • 通过循环每次迭代之后调用增量表达式; 对于该表达式,增加或减少值是完全可以接受的。

    以下程序 ForDemo使用for语句的一般形式将数字1到10打印到标准输出:

    1. class ForDemo {
    2. public static void main(String[] args){
    3. for(int i=1; i<11; i++){
    4. System.out.println("Count is: " + i);
    5. }
    6. }
    7. }

    该程序的输出为:

    1. Count is: 1
    2. Count is: 2
    3. Count is: 3
    4. Count is: 4
    5. Count is: 5
    6. Count is: 6
    7. Count is: 7
    8. Count is: 8
    9. Count is: 9
    10. Count is: 10

    请注意代码在初始化表达式中是如何声明变量的。此变量的范围从其声明扩展到该for语句所控制的块的末尾,因此也可以在终止和增量表达式中使用它。如果for循环外不需要控制语句的变量,则最好在初始化表达式中声明该变量。变量名称ijk通常用于控制for循环。在初始化表达式中声明它们会限制它们的寿命并减少错误。
    for循环的三个表达式是可选的。可以如下创建无限循环:

    1. // infinite loop
    2. for ( ; ; ) {
    3. // your code goes here
    4. }

    for语句还具有另一种设计,通过Collections数组进行迭代的形式。该形式有时被称为for语句的增强形式,可用于使循环更紧凑和易于阅读。为了演示,考虑下面的数组,其中包含数字1到10:

    1. int[] numbers = {1,2,3,4,5,6,7,8,9,10};

    下面的程序 EnhancedForDemo使用增强的for循环遍历数组:

    1. class EnhancedForDemo {
    2. public static void main(String[] args){
    3. int[] numbers =
    4. {1,2,3,4,5,6,7,8,9,10};
    5. for (int item : numbers) {
    6. System.out.println("Count is: " + item);
    7. }
    8. }
    9. }

    在此示例中,变量item保存了numbers数组中的当前值。该程序的输出与前面相同:

    1. Count is: 1
    2. Count is: 2
    3. Count is: 3
    4. Count is: 4
    5. Count is: 5
    6. Count is: 6
    7. Count is: 7
    8. Count is: 8
    9. Count is: 9
    10. Count is: 10

    我们建议尽可能使用这种形式的for语句,而不是一般形式。