Loops in Java

Lesson 5 of 16 · Java
In short: if you know in advance how many times something repeats, use for; if you don't, use while or do-while.

Introduction to loops in Java

Loops in programming are control structures that make it possible to execute a set of instructions several times, as long as a given condition is met. Their main purpose is to automate repeated tasks, which reduces the need to write repeated code. Instead of writing several lines of code by hand for each iteration, loops let us repeat one block of code a certain number of times or until some condition becomes false. The most commonly used loops are the for, while and do-while loops, each suited to different situations.

Comparing the performance of different kinds of loops

In Java, the performance of different loops depends on the number of iterations and on the logic itself:

  1. The for loop: Efficient when we know the exact number of iterations in advance. A good choice for arrays and for iterating through fixed data structures.
  2. The while loop: Better for situations where the number of iterations is not known in advance. It can be less efficient if the condition stays true for a long time.
  3. The do-while loop: Similar to the while loop, but the code is always executed at least once, which can be important in certain cases.

In practice the performance differences between these loops are minimal for most applications, except when working with very large data sets.We can also add the foreach loop here.
The foreach loop is not considered a separate kind of loop; it belongs to the group of iterative loops, like the for loop. While the classic for loop is used to iterate through an array with explicit indices and control variables, the foreach loop simplifies iterating through collections (such as arrays, lists or maps), automatically going through each element without explicit indexing. Although it works differently, it can be seen as a specialized form of the for loop adapted to collections.

The for loop algorithm – diagram

This algorithm shows how the repetition of statements is controlled with three expressions: 1 – a variable is defined and initialized; 2 – a logical expression is set as the loop condition; 3 – the change of the control variable during the loop is defined

The for loop algorithm – diagram (general)
Figure 1: The for loop algorithm – diagram (general)

Here is a concrete example of the 3 expressions used to control the flow: 1 – the variable "i" is defined and initialized to zero; 2 – the logical expression i<n is set as the loop condition; 3 – the control variable changes by "+1" in each cycle

The for loop algorithm – diagram (example)
Figure 2. The for loop algorithm – diagram (example)

The while and do-while loop algorithms – diagrams

It defines the repetition of a group of statements as long as some condition (a logical expression) is met. This loop is usually used when the number of cycles is not known in advance. It is possible that the statements are not repeated even once.

The while loop algorithm – diagram (general)
Figure 3: The while loop algorithm – diagram (general)

It defines the repetition of a group of statements as long as some condition (a logical expression) is met. This loop is usually used when the number of cycles is not known in advance and when, for some reason, it is important that there is at least one cycle. At least one cycle must be executed.

The do-while loop algorithm – diagram (general)
Figure 4: The do-while loop algorithm – diagram (general)

You can read this lesson for the C/C++ language on the following page: Loops in C/C++

To practice examples from this area, go to the page: Loops – examples (C, C++, Java).

Why do we need a loop statement?

Let's look at the following problem. We want to print a sequence of natural numbers. In this example let it be the first 10 natural numbers. The statement that prints the number 1 is:

System.out.print("1");

If we want to print the other numbers too, we could repeat the previous statement 10 times (using Copy – Paste) and change only the value of the number that is shown

System.out.print("1, ");
System.out.print("2, ");
System.out.print("3, ");
System.out.print("4, ");
System.out.print("5, ");
...

The for loop in Java

This could still be done this way for a few numbers, but what if we need to print 100 or 1000 numbers? Of course, we would not do it this way.
The idea of loops is that the statements that repeat are written only once, and a loop statement, such as the statement for, executes these statements several times, i.e. as many times as needed.
In this example the statement that repeats is

System.out.print(..

So we will write it only once and put it into the body of the for statement, which is the loop:
In general, the for statement is written as:

for (inicijalizacija; uslov_petlje; izraz_petlje) {
    niz_naredbi;
}

In our example there is only one statement; it is written inside curly braces and looks like this:

for (inicijalizacija; uslov_petlje; izraz_petlje) {
System.out.print(..
}

The conditions that determine the number of repetitions are written in parentheses: initialization, loop_condition, loop_expression, separated by semicolons.
Initialization means that we introduce (define) a control variable, e.g. "i", which means that we reserve memory for it and give it an initial value (initialize it).
In this example:

int i = 1;

The loop condition is a logical expression that can be true (true) or false (false). In our example it is:

i <= 10;

The loop will repeat as long as this condition is met. If we did not change the variable "i" during the loop (and we can change it through the loop expression), the condition would always be true, i.e. the loop would never stop (an infinite loop). To stop it, we have to make the condition false at some point. We can change the control variable i with the:
loop_expression, which is usually an expression of the form

i = i + korak;

where step is an integer that says by how much the variable "i" increases or decreases (if the step is negative). In our example the value of "i" should increase by 1 in each cycle, so the loop expression will be:

i = i + 1;

This means that the new value in the memory location of i is 1 bigger than the previous one. The for loop now looks like this:

for (int i = 1; i <= 10; i = i + 1) {
System.out.print(..
}

The statement will now repeat 10 times, i.e. as long as i<=10. What remains is what to put into the parentheses of the print statement. If we wrote "1", it would print 1,1,1,1,1,1...
We need a variable that has the value 1 in the first cycle, 2 in the second, etc. That can be exactly the variable i that we use to control the number of cycles. Now we can finally write:

for (int i = 1; i <= 10; i = i + 1) {
    System.out.print(i + ", ");
}

Of course, this task could also be solved with the statement
System.out.print("1,2,3,4,5,6,7,8,9,10");
but here we only wanted to show the for statement for loops and when and why they are used.
The for loop is used when we know in advance how many cycles there will be; if we don't, we use the while or the do-while loop, which are covered later.
For the loop_expression you can use the operator "++" to increase the variable "i" by 1, instead of the expression i=i+1

for (int i = 1; i <= 10; i++) {
    System.out.print(i + ", ");
}

Task: add the first 10 natural numbers with a for loop.

This task could also be solved with the statement

System.out.print("" + (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10));

but we want to show how the sum is obtained with a for loop (useful when there are many numbers). The idea is to add one natural number in each cycle to a variable that holds the sum. In the loop these natural numbers are represented by the variable "i" as in the previous example (convenient, because this variable changes from 1 to 10 with step 1, so through the cycles it actually represents the natural numbers to add).
First we introduce a variable for the sum:
int zbir=0;
Then we add the numbers to the sum one by one. Without a loop that would look like this:
zbir = zbir + 1;
zbir = zbir + 2;
zbir = zbir + 3;
zbir = zbir + 4;
...
zbir = zbir + i;
...
zbir = zbir + 10;
but instead we use a loop:

for (int i = 1; i <= 10; i = i + 1) {
    zbir = zbir + i;
}

The final sum is formed only when the for loop ends. The complete example is shown below.

class Sabiranje {
    public static void main(String[] args) {
        int zbir = 0;
        for (int i = 1; i <= 10; i = i + 1) {
            zbir = zbir + i;
        }
        System.out.println("sum=" + zbir);
    }
}

And after running:

Program output:

sum=55
Figure 5: for loops – the Sabiranje (addition) application, running

EXAMPLE: Average grade

Task text: Read the number of subjects n, then read the grades in n subjects, add them up and compute the average grade. Show the result on the screen.
Hints: Read n through an input dialog. Since there are several grades to read, use a for loop. Add up the grades in the for loop as in the previous example. Only when the final sum of the grades is computed, i.e. after the for loop, can the average be computed.

The while loop – condition at the start

In general the loop looks like this:

while (uslov_petlje) {
    NAREDBE
}
WHILE loop – algorithm
Figure 6: WHILE loop – algorithm

Unlike for, which is used when we know the number of cycles in advance, while is used when we don't know in advance when the loop will stop.
In the picture you can see the loop (a closed circle) that contains the statements to repeat. These statements will repeat as long as the given CONDITION is met. It is a logical expression or a variable of type boolean that can be true or false. The first time the condition is false, the loop stops and the program continues outside the while loop.
Let's look at the following example:

EXAMPLE: Quiz

Task text: Read the points won for the current question in a quiz. Find after how many questions the candidate reaches 30 points, if 1–10 points can be won for each question. Stop counting after at most 10 questions.

int brojBodova;
int ukupnoBodova = 0;
Scanner ucitavac = new Scanner(System.in);

We will read the points in a loop and add them to the total number of points:

while (ukupnoBodova < 30) {
    System.out.println("Enter the number of points");
    brojBodova = ucitavac.nextInt();
    ukupnoBodova = ukupnoBodova + brojBodova;
}

When the total reaches 30 points, the loop stops. To count the cycles we introduce an integer variable whose initial value is zero, and after each cycle this number increases by 1;

int brojBodova;
int ukupnoBodova = 0;
Scanner ucitavac = new Scanner(System.in);
int brojCiklusa = 0;
while (ukupnoBodova < 30) {
    System.out.println("Enter the number of points");
    brojBodova = ucitavac.nextInt();
    ukupnoBodova = ukupnoBodova + brojBodova;
    brojCiklusa++; //The number of cycles increases by 1
}

Finally, we make sure that there are at most 10 cycles. This can be done by extending the existing condition ukupnoBodova < 30 with an extra condition: ukupnoBodova < 30 && brojCiklusa < 10 The whole code is now given below:

import java.util.Scanner;

class Kviz {
    public static void main(String[] args) {
        int brojBodova;
        int ukupnoBodova = 0;
        Scanner ucitavac = new Scanner(System.in);
        int brojCiklusa = 0;
        while (ukupnoBodova < 30 && brojCiklusa < 10) {
            System.out.println("Enter the number of points");
            brojBodova = ucitavac.nextInt();
            ukupnoBodova = ukupnoBodova + brojBodova;
            brojCiklusa++; //The number of cycles increases by 1
        }
        System.out.println("The total number of points is " + ukupnoBodova);
    }
}

The do-while loop – condition at the end

This kind of loop is similar to the while loop, except that the condition is at the end of the loop, not at the start:

do {
    NAREDBE
} while (uslov_petlje);
DO WHILE loop – algorithm
Figure 7: DO-WHILE loop – algorithm

In practice this means that in a do-while loop the statements must be executed at least once, while in a while loop they may not be executed at all. The statements to repeat are inside the loop and repeat as long as the condition has the value true.

Let's look at the following example:

EXAMPLE: Temperature

Task text: Read the temperature values measured every hour at a measuring station. Stop reading when the value -100 is read. Find the number of temperatures read.In this example we don't know in advance how many cycles will be needed (the number of temperatures read) – that is exactly the value we have to find. The loop will run as long as the value read is different from -100 (we assume that such a temperature is not possible, so this value is used to stop the loop).
In the first part of the task we define the variable temperatura (temperature):

Scanner ucitavac = new Scanner(System.in);
double temperatura;

Since we use a do-while loop, at least one temperature will be read inside the loop. Further reading depends on whether the value read is different from -100. The loop then looks like this:

do {
    temperatura = ucitavac.nextDouble();
} while (temperatura != -100);

If the first value read is -100, only that first temperature is read and the loop does not continue. The complete example now looks like this:

import java.util.Scanner;

class Temperatura {
    public static void main(String[] args) {
        Scanner ucitavac = new Scanner(System.in);
        double temperatura;
        int brojCiklusa = 0; // number of temperatures read

        do {
            temperatura = ucitavac.nextDouble();
            brojCiklusa++;
        } while (temperatura != -100);

        // the last value read (-100) only marks the end, so it is not counted
        System.out.println("Number of temperatures read: " + (brojCiklusa - 1));
    }
}

The number of temperatures read is equal to the number of cycles. To find the number of cycles we use the integer variable brojCiklusa (number of cycles), as in the previous example.
Tasks for which a for loop is more convenient, because we know the number of cycles in advance, can still be solved with a while or do-while loop. The example of adding the first 10 natural numbers with a while loop would look like this:

int zbir = 0;
int i = 1; // initialization – before the loop
while (i <= 10) // loop condition
{
    zbir = zbir + i;
    i = i + 1; // loop expression – inside the loop
}
System.out.println("sum=" + zbir);

Since only the loop_condition is inside the parentheses of the while loop, the initialization, which was also inside the parentheses in the for loop, is written before the loop here, while the loop_expression, which sets the step of the control variable, is written as one of the statements inside the while loop.

Nested loops

You can read about nested loops in C/C++ on the following page: Nested loops in C/C++

A loop can also be inside another loop, as one of the statements of the outer loop:

for (inicijalizacija1; uslov_petlje1; izraz_petlje1) {
    for (inicijalizacija2; uslov_petlje2; izraz_petlje2) {
        niz_naredbi
    }
}

Nested loops – example 1

Nested loops make it possible to run loops inside other loops. For example, a for loop can contain another for loop, where the inner loop runs for each pass of the outer loop. This is useful for problems that need iterations through multidimensional structures, such as matrices.

Example:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.println(i + ", " + j);
    }
}

This can be explained with the following example:

EXAMPLE: Matrix

Task text: Print a matrix of 10 rows and 10 columns that looks like the picture:

Program output:

1  2  3  4  5  6  7  8  9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
Figure 8: Matrix 10 x 10 – running


Solution:
To print one row of numbers we use a for loop

for (int j = 0; j < 10; j++) {
    System.out.print((j + 1) + " ");
}

Here the value (j+1) is used to print the first row, because the initial value of j is 0, not 1.
Since 9 more such rows have to be printed, the for statement has to be repeated 9 more times. We will add another for loop (the outer one), so that the previous for loop becomes a statement nested inside the outer for loop.

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        System.out.print((j + 1) + "  ");
    }
    System.out.println(); //New line – after each row
}

The control variable i now represents the current row, and the control variable j, which belongs to the inner loop, represents the index of the current column. This code needs a small change, because
System.out.print((j+1)+" ");
always prints the numbers 1 – 10, while for e.g. i = 3 (the 4th row) it should print values (i*10) bigger, in this case 30 bigger (31-40). This means the statement should be changed to:
System.out.print(10 * i +(j+1)+" ");

for-each petlja

for each loops were introduced in Java 5 and are used with arrays of data when we need to go through the elements of the array iteratively. For example, if we defined the following array:

String[] planete = {"Merkur", "Venera", "Zemlja", "Mars", "Jupiter", "Saturn", "Uran", "Neptun"};

To print the previously defined array of Strings, which is the set of planets of the Solar System, it is convenient to use the for-each loop. The statement is also written as for, but without the control expressions with the variable "i". Instead, the following syntax is used:

for (String planeta : planete) {
    System.out.println(planeta);
}

Here planeta (planet) is a variable of the same type as the elements of the array "planete". In each next cycle the value of the variable planeta will be the element at the next position of the array. So after the previous statement runs, the standard output will show: Merkur
Venera
Zemlja
...

The same example could also be done with an ordinary for loop:

for (int i = 0; i < planete.length; i++) {
    System.out.println(planete[i]);
}

This example is simpler with the for-each loop, but there are some examples that cannot be done that way, and an ordinary for loop must be used. For example, if we want to print an array of integers backwards:

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

That would print the following: 10
9
8
...

for-each loops with collections and arrays of objects in Java

The for-each loop is convenient for going through a collection or an array of Java objects. Suppose the following collection of objects (ArrayList) is defined in Java:

ArrayList<Zaposleni> sviZaposleni = new ArrayList<>();

The list is a collection of objects of the class Zaposleni (employee). If we create 3 such objects and put them into the list, we would use a for-each loop to print the data, as in the following picture:

import java.util.ArrayList;

public class Preduzece {
    public static void main(String[] args) {
        ArrayList<Zaposleni> sviZaposleni = new ArrayList<>();

        // creating the employee objects
        Zaposleni zaposleni1 = new Zaposleni("Mihajlo Petrovic", 800000, 10);
        Zaposleni zaposleni2 = new Zaposleni("Luka Pekez", 1200000, 20);
        Zaposleni zaposleni3 = new Zaposleni("Sara Jaksic", 90000, 15);

        // adding objects to the list
        sviZaposleni.add(zaposleni1);
        sviZaposleni.add(zaposleni2);
        sviZaposleni.add(zaposleni3);

        // printing the employee data
        for (Zaposleni z : sviZaposleni) {
            System.out.println("Employee " +
                z.imeIPrezime + " has a salary of " +
                z.plata + " and " + z.radniStaz +
                " years of service");
        }
    }
}
Figure 9: The for-each loop in Java – the Preduzece (company) class example

The class Zaposleni would be:

public class Zaposleni {
    String imeIPrezime;
    double plata;
    int radniStaz;

    public Zaposleni(String imeIPrezime, double plata, int radniStaz) {
        this.imeIPrezime = imeIPrezime;
        this.plata = plata;
        this.radniStaz = radniStaz;
    }
}
Figure 10: The for-each loop in Java – the Zaposleni (employee) class example

In newer versions of Java the foreach loop can be written as follows:

// printing the employee data (Java 8 and newer: the forEach method and a lambda expression)
sviZaposleni.forEach(z -> {
    System.out.println("Employee " +
        z.imeIPrezime + " has a salary of " +
        z.plata + " and " + z.radniStaz +
        " years of service");
});
Figure 11: The for-each loop in Java – an example of this loop in Java 8 or newer

Optimizing loops

Optimizing loops includes reducing the number of iterations or using more efficient algorithms to improve performance. Key tips:

  • Avoid unnecessary computation inside the loop (e.g. compute constant values outside the loop).
  • Use break when you can stop the loop earlier.
  • Always check the conditions to avoid infinite loops.

An example of an optimized loop:

for (int i = 0; i < arr.length; i++) {
    if (arr[i] == target) {
        break; // Stops the loop when the target is found
    }
}

Additional resources

Related links:

  • Control structures in Java: Explore the other control structures in Java, such as if-else statements and switch cases, which are often used together with loops. Selection statements in Java
  • Recursion in Java: Learn more about recursion, a technique that can sometimes replace loops for certain tasks, with detailed examples and explanations. Recursive algorithms
  • Arrays in Java: Understanding arrays is essential when you work with loops. Dive into how arrays work and how to iterate through them with loops. Arrays in Java

External resources:

You can find loop examples on the page: Loops – basic examples

Additional examples: Test preparation: loops

Check your knowledge

Open the quiz

Mini quiz: loops in Java

1. Which loop do you choose when you know the number of repetitions in advance?




2. How many times is the body of the loop for (int i = 1; i <= 10; i++) executed?




3. Which loop is executed at least once, even when the condition is false right away?




4. What does for (String p : planete) print?




Check your knowledge

Open the quiz

Quiz: Loops in Java

1. How many times is for (int i = 1; i <= 10; i++) executed?




2. When do we use while instead of for?




3. What does for (String p : planete) System.out.println(p); print?




4. How many times is the body of the inner loop executed for a 10 × 10 table?