Skip to content

Loops

A loop helps with repeating the same instruction (on each element) a given number of times until a certain condition is met or not (then it goes to infinity).

We can specify a few different types of loops:

  • They execute the provided block of code, until certain conditions are met.

  • The code is executed a finite number of times (loops).

  • Loops that have no end point are called infinite loops.

In Java we specify the following types of loops:

  • for
  • while
  • do while

for

In general, a "for" loop looks like this:

for(initial statement; statement end point; statement incrementation) {
    // instruction
}

We can therefore distill the "loop" code into three phases:

  • initial statement - they are executed once, just before the loop is started. They are often used to create the initial condition based on which the loop functions.

  • statement end point - this checks if the loop is still valid or whether it has reached it's end point. If the condition is still true the code within the loop will execute. If it is not, the code will go outside the loop.

  • statement incrementation - this block of code is executed after each loop run (in common terms: the code has finished executing, at least, once). It is often used to modify (increment/decrement) the variable provided in the initial statement.

The simplest use of "for" can be seen below:

for (int i = 0; i < 10; i++) {
    System.out.println("Hello World!");
}
The use of this loop is fairly easy: You set up the steering variable 'i' at 0 initially (i=0) . This helps to print "Hello World!" once. With the statement incrementation of i++ you add 1 to the initial value of i. Until the statement end point of (i<10) is reached the code block of printing "Hello World" will repeat 10 times.

The 'for' loop is also great for working with collections:

String[] array = {"We", "have", "a cat"};
for (String element: array) {
    System.out.println(element + " ");
}
This is referred to in arrays in further chapters.

while

The 'while' loop is used a bit differently. Imagine a situation, when you don't know how many times you wish to repeat a loop but you know which condition to use so that the code block is executed. The general schema is as follows:

while (condition) {
    // instruction
}
The 'while' loop can be described in this way: keep repeating the instruction provided within the code block until the condition within the loop is not not fulfilled. When the condition is met the loop and it's code is repeated. If the condition is not met the loop might not even initialize (in other words: it might not even start).

A simple example is provided below (the behavior will be the same as in the 'for' example above):

int i = 0;
while (i < 10) {
    System.out.println("Hello World!");
    ++i;
}
As a result of running the loop the "Hello World!" string will be displayed 10 times.

do while

There is a linguistic difference in using this loop as opposed to 'while'. With "do while" all the instructions in the code block will run at least once - as the name implies. The 'while' condition is checked at the end of the loop (after the whole code block has been executed once).

The general schema can be showcased as seen below:

do {
    // instructions
}
while (condition);
A similar example to the previous ones would look like this:

int i = 0;
do {
    System.out.println("Hello World!");
    ++i;
} while (i < 10);

At first glance the text is printed the same number of times as in previous examples. There is a slight difference though: if the variable 'i' had an initial value of 12 and not 0 the text would be printed at least once. In a 'while' loop it would not show at all.

break and continue

There are two keywords strongly linked to loops. They are 'break' and 'continue'.

The word 'break' helps end the loop which is ongoing. The next iteration of that loop will not start:

for (int i = 0; i < 10; i++) {
    System.out.println("Hello World!");
    if (i == 1) {
        break;
    }
}
In the above example the text Hello World! will be shown two times only. With the use of break at (i==1) the loop will print the text twice - when i is equal to 0 and 1. Then it will "break" and go outside the loop.

On the other hand by using the 'continue' keyword the condition will enable the loop to go on:

for (int i = 0; i < 10; i++) {
    if (i == 8) {
        continue;
    }
    System.out.println("Hello World!");
}
By using 'continue' when the variable i reaches the number 8 the code will skip over printing "Hello World!" and as result the text will be printed only 9 times. The use of 'continue' has no influence over the final condition in the 'for' loop (it will always be executed).