Repetition

If a block of code must be executed several times, a looping structure can be used.

Java has several such structures. Here we will consider two, the for loop and the while loop.

The for loop

A for loop repeats a block of code a predetermined number of times. The format of a for loop is as follows:

for (initialisation; condition; post-body action) {

    // code block to be executed

}

The first line is called the for-loop header. The code in the loop body, enclosed between the braces { and } is the code to be repeatedly executed.

The three statements inside the for-loop header determine the number of times the loop body will be executed:

initialisation declares and initialises a variable (called a loop control variable) that controls the number of times the loop is executed. This section is executed only once, when the for statement is first entered. The loop control variable's scope is within the for loop.

condition defines a Boolean condition, which is evaluated for the first time immediately after the initialisation, to determine whether the loop body should be executed. If it evaluates to false, the loop body is not executed. If the condition is initially true, the loop body is executed, and the condition is then evaluated every time after the post-body action to decide whether to execute the loop body again.

post-body action updates the loop control variable, each time after the loop body has been executed.

Example

for (int i = 1; i < 4; i = i + 1) {

    System.out.print(i);

    System.out.println("*");

}

//next statement

  1. In the for-loop header, the initialisation statement declares an int variable called i and initialises it to 1.
  2. The condition statement is the Boolean condition i < 4, which initially evaluates to true, and so the loop body is executed.
  3. The post-body action is now executed, which increments (adds one to) the value of i.

    The condition is now evaluated again. As the condition is still true, the loop body is executed again.

  4. Step 3 is repeated until the condition is false, at which point the for-loop exits and the program moves on to the next statement.

    In this example, the loop body executes three times.

Here is a trace of the value of i and the corresponding output on each iteration through the loop:

i

i < 4

output

i now becomes

1

true

1*

2

2

true

2*

3

3

true

3*

4

4

false

 

 

The while loop

Sometimes it is not known ahead of time how often a loop will need to execute. In these cases, a while loop is a better choice than the for-loop. The form of a while loop is as follows:

while (condition) {

    //loop body

}

//next statement

The Boolean condition is evaluated when the while statement is first entered, and the loop body is executed only if the condition evaluates to true. The Boolean condition is evaluated again after each execution of the loop body. When the Boolean condition evaluates to false, the loop body is not entered again, and the program moves to the next statement after the while loop.

Here is an example where the value of count is not known until runtime, because it depends on calling a method called startingCount:

int count = startingCount();

while (count < 3) {

    System.out.println(count);

    count = count + 1;

}

When the while loop structure is encountered, the Boolean condition, count < 3, is executed. If the condition is true, the loop body is executed; if it is false, control passes to the statement after the loop structure. The Boolean condition is re-evaluated each time the loop body finishes executing until it becomes false, when the loop body is not executed again.

If count is initialised to 2 in this example, the Boolean condition is true, and the loop body executes, but as part of the loop body, count is set to the value 3. When the Boolean condition is evaluated again, it is false, and the loop body is not executed again.

It is important when designing a while loop to ensure that the Boolean condition will, eventually, become false, otherwise you get an infinite loop - that is, the loop continues to execute forever.

Java compared with Python

Java loops are like Python loops although the syntax is slightly different.

Here are two examples of equivalent loops in Java and In Python.

Java

for (int i = 3; i <= 5; i = i + 1) {

    System.out.print(i);

}

Python

for i in range(3, 6):

  print(i)

The output in each case is

345

However, note that in Java the variable i is not accessible after the loop, while in Python the value of i after the loop is 5.

Notice also that in the Java version there is no colon (or semicolon) after the loop-header and the three parts of the for-loop header must be enclosed in parentheses. The Python version uses the built-in range function, which assigns to i the value 3, 4 and 5 in turn before each execution of the loop body, but there is no such built-in function in Java

Similar syntax differences apply to while loops:

Java

int count = 3;

while (count <= 5) {

    System.out.print(count);

    count = count + 1;

}

Python

count = 3

while count <= 5:

  print(count)

  count = count + 1

The output in each case is

345

The value of count after the loops is 6 in both cases.

Test your understanding

  1. Given this Java for loop, how many times will the loop body execute?

    for (int count = 2; count < 12; count = count + 2) {

        System.out.print(count);

    }

  2. What is the output when the for loop in Question 1 is executed?
  3. What could go wrong with the following Java while loop?

    int myInt = startingValue();

    while (myInt < 10) {

        System.out.print(myInt);

    }