Java for, while, do..while & foreach loops iteration control statements Tutorial

In this Java tutorial we learn how to repeat sections of our code with while, do while, for and foreach (enhanced for) loops based on the results of a condition.

We also discuss nesting loops. Lastly, we learn how to refine control on our loops by using the break and continue statements.

What is iteration control and looping

Java allows us to control the flow of our application even further by looping through sections of code when a condition proves true.

As an example, let’s consider a database of users that are subscribed to a mailing list.

Normally, we would enter a user’s email address, copy-paste a predefined message, and then send the email.

But, there could be tens of thousands of users in that list. We would need a way to automate the process.

Iteration control allows us to set up that process in code, then repeat it by looping through all the users on the list, sending them each an email.

Java provides us with four different kinds of loops:

  • while - This loop iterates through a section of code while a condition is true.
  • do while - This loop is the same as the while loop but with a single forced loop at the start.
  • for - This loop iterates through a section of code a set number of times.
  • foreach - This loop is specific to loop through collections.

The indefinite while loop in Java

A while loop is used when we don’t know how many times a loop will repeat, like the number of users in a database.

A while loop will keep looping through its code, while a specified condition is true. For example, while there are users in a database, loop through the section of code that sends an email.

To write a while loop, we use the keyword while , followed by the condition in between parentheses, and a code block that contains the code we want to execute on each iteration.

Syntax:
while (condition) {

    // execution statement(s)
}
Example:
public class Program {
    public static void main(String[] args) {

        byte i = 1;

        while (i <= 10) {

            System.out.println("Iteration no: " + i);
            i++;
        }
    }
}

When we run the example above, we should see the following output.

Output:
Iteration no: 1
Iteration no: 2
Iteration no: 3
Iteration no: 4
Iteration no: 5
Iteration no: 6
Iteration no: 7
Iteration no: 8
Iteration no: 9
Iteration no: 10

The single section of code we wrote in the code block was repeated 10 times.

Let’s break down the example above step by step.

  1. First, we set up a variable called i with the number 1. This variable will act as a counter, and help us see which iteration of the entire loop we’re on.
  2. Then, we specify our condition. While the value of i is less than or equal to 10, execute the code in the code block.
  3. In the code block we have a simple statement that prints the number i. We also increment it by one by adding ++ to it.

What will happen is the following:

  1. The compiler will see that i is 1. This means the loop condition is true, so it will print the message to the page and increment i by 1.
  2. Then, it will move back to the start of the loop and evaluate the condition again. The condition is still true because i, now 2, is still less than 10, so it executes the code block again.
  3. This continues until i is 10, in which case the condition turns false and the compiler stops looping.

Let’s try a more practical example.

Example:
public class Program {
    public static void main(String[] args) {

        byte i = 0;
        String user[] = {"John", "Jane", "Jack", "Jill"};

        while (i < 4) {

            System.out.println("User[" + i + "]: " + user[i]);
            i++;
        }
    }
}

In the example above, we use the counter as an array index to print each element of the array.

If you’re a beginner and don’t know what an array is, don’t worry. We cover looping through arrays again in the Arrays lesson .

The indefinite do-while loop in Java

The do while loop is sort of like an upside down while loop. The execution code is specified first, then the condition is checked.

To write a do while loop we use the keyword do , followed by a code block with the execution code. Then, we specify the while condition.

Syntax:
do {

    // execution code

} while (condition);

Note that because the do while statement doesn’t end with a curly brace, it’s terminated with a semicolon.

Example:
public class Program {
    public static void main(String[] args) {

        byte i = 1;

        do {

            System.out.println("Iteration no: " + i);
            i++;

        } while (i <= 0);
    }
}

In the example above we set the counter to 1. But, the condition will check if the counter is less than or equal to 0, so the condition is always false and the loop shouldn’t run.

When we compile and run the script however, we see that the loop did run once. This is because the code block is executed before the compiler could evaluate the condition and stop the loop.

A do while loop will always run at least once.

The definite for loop in Java

A for loop is used when we know how many times the loop will repeat, like the number of hours in a day.

The syntax in a for loop is much more compact. It has the counter, the condition, and the increment all in one place.

We write the keyword for , followed by a condition block and then an execution block containing the code we want to have loop.

Inside the condition block in the header we first set up our counter, followed by a semicolon terminator. Then we specify our condition, again followed by a semicolon terminator. Lastly, we increment/decrement the counter.

Syntax:
for (counter_setup; condition; counter_increment) {

    // execution code
}
Example:
public class Program {
    public static void main(String[] args) {

        for (byte i = 1; i <= 10; i++) {

            System.out.println("Iteration no: " + i);
        }
    }
}

The example above is exactly the same as our first while loop example, the only difference is the syntax. The counter setup and counter increment is done inside the condition block.

In a while loop we may not always need a counter. But, in a for loop we will always need a counter so the setup and increment is required.

The definite foreach loop (enhanced for loop) in Java

The foreach loop is specifically designed to make looping through collections and arrays easier. The syntax is similar to a for loop.

We specify a temporary value that will hold the element value, followed by a colon and the collection, or array, name. We don’t specify a counter.

Syntax:
for (type temp_variable : collection_name) {

    // use temp variable as
    // collection item value
}

The foreach loop will automatically count the elements in the collection, or array, and iterate over them.

Each time it iterates through an element, it stores the element in the ‘temp_variable’ and we can use it.

Because of this, the temp variable must be of the same type as the element in the collection or array.

Example:
public class Program {
    public static void main(String[] args) {

        String user[] = {"John", "Jane", "Jack", "Jill"};

        for (String i : user) {

            System.out.println("User: " + i);
        }
    }
}

In the example above, we iterate through an array with 4 elements, which the loop automatically calculates.

Because the values in the array are strings, our temporary variable ‘i’ has to be a string type too.

How to nest loops in Java

Similar to nesting conditional control statements, we can nest loops inside other loops.

The loops will be executed hierarchically, which means the compiler will run an inner loop fully, before it moves on to the next iteration of the outer loop.

As an example, let’s consider that we want to create a chunk of blocks like those in Minecraft.

We want it to be 16 x 16 blocks on the x and z axes (creating a square), and we want it to be 16 squares high on the y axis, creating a tower (chunk).

We would need to create blocks in each of the three axes, x, y and z. For that we would need to nest our loops.

Example:
public class Program {
    public static void main(String[] args) {

        byte x = 16, y = 16, z = 16;

        for (byte i = 0; i < x; i++) {
            for (byte j = 0; j < y; j++) {
                for (byte k = 0; k < z; k++) {

                    // code to make a single block
                    System.out.println("Made block at " + i + ", " + j + ", " + k);
                }
            }
        }
    }
}

In the example above, we print a message with the block number created on each axis.

We should try not to nest more than 3 levels deep. Nesting too deep is considered a bad practice and can become complicated very quickly.

Loop control statements in Java: break

Java provides us with control statements to control the flow of our loops. The first of these is the break statement.

The break control statement allows us to break out of a loop, by using the keyword break where we want to break out of the loop.

We’ve encountered the break statement before in the switch section of the Conditional Control lesson .

Example:
public class Program {
    public static void main(String[] args) {

        for (byte i = 0; i <= 10; i++) {

            // break from the loop
            // when 'i' is at 6
            if (i == 6) {
                break;
            }

            System.out.println("Iteration no: " + i);
        }
    }
}

In the example above, we want our loop to iterate until the counter gets to 10.

But, in the execution code, we set up an if statement to break the loop when the counter reaches 6.

When we look at the output, we can see that the numbers only print up to 5, which means the loop was successfully stopped when it reached 6.

Output:
Iteration no: 0
Iteration no: 1
Iteration no: 2
Iteration no: 3
Iteration no: 4
Iteration no: 5

Loop control statements in Java: continue

The continue control statement is similar to break, but will skip anything after the keyword and move to the next iteration of the loop.

Once again we can simply use the continue keyword wherever we want inside a loop.

Example:
public class Program {
    public static void main(String[] args) {

        for (byte i = 0; i <= 10; i++) {

            // break from the loop
            // when 'i' is at 6
            if (i == 6) {
                continue;
            }

            System.out.println("Iteration no: " + i);
        }
    }
}

In the example above, our loop will iterate until the counter gets to 10.

But, this time the if statement in the execution block tells the compiler to skip the print statement when it gets to 6, instead of completely breaking out of the loop.

When we look at the output, we can see that 6 isn’t printed to the console, which means we successfully skipped that iteration.

Output:
Iteration no: 0
Iteration no: 1
Iteration no: 2
Iteration no: 3
Iteration no: 4
Iteration no: 5
Iteration no: 7
Iteration no: 8
Iteration no: 9
Iteration no: 10

Summary: Points to remember

  • Iteration control allows us to repeat sections of our code by looping through them.
  • Java provides us with while, do while, for and foreach (enhanced for) loops.
  • The while loop is used when we don’t know how many times a loop will repeat.
  • The do while loop is used when we don’t know how many times a loop will repeat, but it should be at least once.
  • The for loop is used when we know how many times a loop should repeat.
  • The for loop must specify its counter and the increment/decrement of that counter in the condition block of the statement.
  • The foreach loop is used to loop through collections or arrays.
    • The foreach loop automatically counts the number of elements in the array and iterates through them.
    • We specify a temporary variable in the header that will hold the value of the element we are iterating over.
  • Loops can be nested inside other loops. It’s considered bad pratice to nest more than 3 levels deep.
  • The break control statement will completely break out of the loop and move on to the code below the loop.
  • The continue control statement will skip the current iteration of the loop. It will skip any code after the continue statement.