Learn Java

Java For Loop

Sometimes we need to repeat a block of code a certain number of times. To do this, Java provides a type of loop called the for loop. It is often used to iterate over a range of values or through an array. If the number of iterations or the range borders are known, it is recommended to use the for loop. If they are unknown, other types of loops like the while loop may be the preferable solution.

The basic syntax

The for loop has the following basic syntax:

for (initialization; condition; modification) {
    // do something
} 

Parts of the loop:

  • the initialization statement is executed once before the loop begins; usually, loop variables are initialized here;
  • the condition is a Boolean expression that determines the need for the next iteration; if it's false, the loop terminates;
  • the modification is a statement that changes the value of the loop variables; it is invoked after each iteration of the loop; usually, it uses increment or decrement to modify the loop's variable.

Inside the loop's body, the program can perform any correct Java statements. It can even contain other loops.

The order of execution for any for loop is always the same:

  1. the initialization statement;
  2. if the Boolean condition is false, then terminate the loop;
  3. if the Boolean condition is true, then the body of loop is executed;
  4. the modification is performed;
  5. go to step 2 (condition evaluation).

Armed with this knowledge, let's write a loop statement for printing integer numbers from 0 to 9 on the same line.

int n = 9;
for (int i = 0; i <= n; i++) {
    System.out.print(i + " "); // here, a space is used to separate numbers
}

The code displays:

0 1 2 3 4 5 6 7 8 9 

The variables declared in the initialization statement are visible only inside the scope that includes all parts of the loop: the condition, the body, and the modification. The integer loop variables are often named ijk, or index.

Here’s another example. Let's calculate the sum of the integer numbers from 1 to 10 (inclusive) using the for loop.

int startIncl = 1, endExcl = 11;

int sum = 0;
for (int i = startIncl; i < endExcl; i++) {
    sum += i;
}

System.out.println(sum); // it prints "55"

Skipping parts

The initialization statement, the condition, and the modification parts are optional, the for loop might not have all of them.

It is possible to do variable declaration outside the loop:

int i = 10;
for (; i > 0; i--) {
    System.out.print(i + " ");
}

Moreover, it is also possible to write an infinite loop without these parts at all:

for (;;) {
    // do something
}

Nested loops

In Java programming language it's possible to nest one for loop in another for loop. This approach is used to process multidimensional structures like tables (matrices), data cubes, and so on.

As an example, the following code block prints the multiplication table of numbers from 1 to 9 (inclusive).

for (int i = 1; i < 10; i++) {
    for (int j = 1; j < 10; j++) {
        System.out.print(i * j + "\t");
    }
    System.out.println();
}

It outputs:

1   2   3   4   5   6   7   8   9  
2   4   6   8   10  12  14  16  18  
3   6   9   12  15  18  21  24  27  
4   8   12  16  20  24  28  32  36  
5   10  15  20  25  30  35  40  45  
6   12  18  24  30  36  42  48  54  
7   14  21  28  35  42  49  56  63  
8   16  24  32  40  48  56  64  72  
9   18  27  36  45  54  63  72  81 

Using the for-each loop

Since Java 5, there has been a special form of the for-loop known as for-each loop. It is a type of for loop that provides a simple and unified way to process elements of a collection or array. With it, you don't have to deal with indices. The for-each Java loop works by automatically handling the iteration process, allowing developers to focus on the code within the loop body. This loop is particularly useful where the order of elements is not crucial.

Here's what it looks like:

for (type var : array) { 
    // statements using var
}

And here's how to read it: for each element var of type type in the array array, execute the statements in the body.

Let's take a closer look at the components. type specifies the variable data type that will store one array element during each iteration. Usually, this type matches the array element's type. The var variable holds one array element in each iteration. Its value changes with each iteration to store the next element.

Let's now compute the number of 'a' letters in a given character array using a for-each loop:

char[] characters = { 'a', 'b', 'c', 'a', 'b', 'c', 'a' };

int counter = 0;
for (char ch : characters) {
    if (ch == 'a') {
        counter++;
    }
}

System.out.println(counter); // it outputs "3"

We can achieve the same result with a standard for-loop:

char[] characters = {'a', 'b', 'c', 'a', 'b', 'c', 'a'};

int counter = 0;
for (int i = 0; i < characters.length; i++) {
    if (characters[i] == 'a') {
        counter++;
    }
}

System.out.println(counter); // it outputs "3"

The for-each method does have some limitations. You can't use it to modify an array because the variable we use for iterations doesn't hold the actual array element, only a copy. You also can't retrieve an element by its index as the index isn't used. Lastly, we can't move through an array with more than one step per iteration: we iterate through each element one-by-one.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate