Skip to content
On this page

For Loop

In addition to while and do while loops, the most widely used in Java is for loop.

The for loop is very powerful, it uses counters to implement loops. The for loop will first initialize the counter, then detect the loop condition before each loop, and update the counter after each loop. Counter variables are usually named i .

Let’s rewrite the sum from 1 to 100 using for loop:

java
public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i=1; i<=100; i++) {
            sum = sum + i;
        }
        System.out.println(sum);
    }
}

Before the for loop is executed, the initialization statement int i=1 will be executed first, which defines the counter variable i and assigns the initial value to 1 Then, the loop condition i<=100 is checked before the loop, and i++ is automatically executed after the loop, so , compared with the while loop, for loop unifies the code for updating the counter together.

Inside the loop body of the for loop, there is no need to update the variable i .

Therefore, the usage of for loop is:

java
for (initial conditions; Cycle detection conditions; Update counter after loop) {
    // 执行语句 
}

If we want to sum all the elements of an integer array, we can use for loop to achieve it:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        int sum = 0;
        for (int i=0; i<ns.length; i++) {
            System.out.println("i = " + i + ", ns[i] = " + ns[i]);
            sum = sum + ns[i];
        }
        System.out.println("sum = " + sum);
    }
}

The loop condition of the above code is i<ns.length . Because the length of the ns array is 5 , after looping 5 times, the value of i is updated to 5 , and the loop condition is not met, so for loop ends.

Think

What problems will occur if the loop condition is changed to i<=ns.length ?

Note that the initial counter of a for loop is always executed, and the for loop may also loop 0 times.

When using a for loop, never modify the counter inside the loop body! Modifying the counter in the loop body often leads to inexplicable logic errors. For the code below:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int i=0; i<ns.length; i++) {
            System.out.println(ns[i]);
            i = i + 1;
        }
    }
}

Although no error is reported, only half of the array elements are printed. The reason is that i = i + 1 inside the loop causes the counter variable to actually increase by 2 each time it loops (because the for loop also automatically executes i++ ).

Therefore, in the for loop, do not modify the counter value. The initialization of the counter, judgment conditions, and update conditions after each loop are unified into the for() statement so that it can be seen at a glance.

If you want to access only array elements with even index numbers, you should rewrite for loop as:

java
int[] ns = { 1, 4, 9, 16, 25 };
for (int i=0; i<ns.length; i=i+2) {
    System.out.println(ns[i]);
}

This effect is achieved by updating the counter statement i=i+2 , thus avoiding the need to modify the variable i in the loop body.

When using a for loop, the counter variable i should be defined in the for loop as much as possible:

java
int[] ns = { 1, 4, 9, 16, 25 };
for (int i=0; i<ns.length; i++) {
    System.out.println(ns[i]);
}
// Unable to access i
int n = i; // compile error!

If variable i is defined outside the for loop:

java
int[] ns = { 1, 4, 9, 16, 25 };
int i;
for (i=0; i<ns.length; i++) {
    System.out.println(ns[i]);
}
// It is still possible to use i
int n = i;

Then, after exiting the for loop, variable i can still be accessed, which destroys the principle that variables should minimize their access scope.

Flexible use of for loops

The for loop can also lack initialization statements, loop conditions and update statements for each loop, for example:

java
// No end condition is set:
for (int i=0; ; i++) {
    ...
}
java
// Do not set end conditions and update statements:
for (int i=0; ;) {
    ...
}
java
// Set nothing:
for (;;) {
    ...
}

It is generally not recommended to write this way, but in some cases, it is possible to omit certain statements in the for loop.

For each loop

A for loop is often used to iterate over an array because each element of the array can be accessed based on its index using a counter:

java
int[] ns = { 1, 4, 9, 16, 25 };
for (int i=0; i<ns.length; i++) {
    System.out.println(ns[i]);
}

However, many times, what we actually want to access is the value of each element of the array. Java also provides another for each loop that can traverse an array more simply:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) {
            System.out.println(n);
        }
    }
}

Compared with the for loop, the variable n in the for each loop is no longer a counter, but directly corresponds to each element of the array. The for each loop is also written more concisely. However, the for each loop cannot specify the traversal order, nor can it obtain the index of the array.

In addition to arrays, the for each loop can traverse all "iterable" data types, including List , Map etc., which will be introduced later.

Exercise 1

Given an array, use for loop to output each element in reverse order:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int i=?; ???; ???) {
            System.out.println(ns[i]);
        }
    }
}

Exercise 2

Use a for each loop to sum each element of the array:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        int sum = 0;
        for (???) {
            // TODO
        }
        System.out.println(sum); // 55
    }
}

Summary

The for loop can implement complex loops through counters;

The for each loop can directly traverse each element of the array;

Best practice: The counter variable is defined inside the for loop, and the counter is not modified inside the loop body;

For Loop has loaded