loops: for, while and do while loop

Back to course page

 

Downloads
loops: for, while and do while loop (Article)

In this article from my free Java 8 course, I will discuss the use of loops in Java. Loops allow the program to execute repetitive tasks or to iterate over vast amounts of data quickly.

Background

Imagine that I want to send out an email to every subscriber of my newsletter. Now, if I had to manually send an email to every single subscriber, I would be kept busy for days. Instead, I want to write a program that helps me do this. So I write a program like this:

sendEmail(Tom);

sendEmail(Ben);

sendEmail(Christian);

[…]

sendEmail(Julia); // 99,999th line

Example 1

For every new subscriber, I will have to extend my code and add a new “sendEmail” call. This isn’t much better than my manual approach before. To fix this, I want to group all my subscribers into a list and then tell my computer to uniformly send an email to each subscriber on my list. That’s where “loops” come into play. They are a way to express, “I want to execute this code 99,999 times”, for instance.

For-Loop

The first loop I will discuss is the “for-loop”. It is called a for-loop because it tells the program, “Execute this loop FOR a certain number of times”. Our for-loop has three sections.

The first section assigns and defines a variable, such as “int i = 0”. It uses this variable to iterate.

Note:

Generally, you can use any variable name, but one-letter variable names are commonly used in this context. This, at first, might seem counterintuitive and contradict the recommendation of using descriptive variable names. “i” in this context is okay, because one letter variables like ‘i’ or ‘j’ are commonly used for counter variables in for-loops. The letter ‘i’ is specifically used because it stands for the word “index”. ‘j’ is used in cases when you need two different indexes – just because ‘j’ is the next letter in the alphabet after “i’. Finally, the length of a variable name should be related to the length of the block of code where it is visible. When you have a large block of code, and you can’t directly see where this variable was defined, it should have a descriptive name. For-loops however are preferably short – in the best case just spanning over 3 lines of code – so “i” as THE index variable should actually be very descriptive in this case, and any other name than “i” or “j” for a simple index variable of a for-loop could actually even confuse other developers.

The second section defines how many times we want to execute the code inside the for-loop. In Example 2, we used ‘i < 4’. It is important to remember that it is commonplace in programming to start index values with 0, not 1. Since we want our code to iterate four times, we say ‘i < 4’ meaning that the code will execute when our ‘i’ value is 0, 1, 2, or 3.

The last section defines the incrementation of our variable. It can either increase the value or decrease it. In our example, we are increasing it by 1 using ‘i++’ which increases our ‘i’ value by 1. This occurs after the code block inside the for-loop is finished. If we were to print out our ‘i’ values inside the code of our for-loop, it would print ‘0,1,2,3’, not 4. ‘i’ would increment to 4 after our code runs for the fourth time, but since that does not satisfy the condition in the middle section of our for-loop, the code inside the loop stops executing.

public void shouldReturnNumberOfPersonsInLoop() {

Person person1;

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

person1 = new Person();

}

assertEquals(4, Person.numberOfPersons());

}

Example 2

To restate the logic of the for-loop, initially ‘i’ is assigned a value of 0. After we execute our code inside the loop, ‘i’ is now incremented by 1, so now it has a value of 1. The condition we wrote in the middle section stipulates that ‘i < 4’ for our code to execute. Since that is evaluated to be true, the code executes again, increments i by 1 and keeps repeating. The first time the condition evaluates to false is when ‘i’ has a value of 4. At this point the loop is exited and we will have executed our code 4 times.

You can also increment by numbers larger than 1. Say we incremented the previous example using “i = i + 2”, you would only create two person objects. This is because we are now only going through the loop twice, when i = 0 and i = 2.

One of the things you should watch out for when creating loops is the possibility of an infinite loop. For example if our condition in Example 2 is “i < 1” and you continually decrease the value of ‘i’ using “i–”, the loop will go on forever, create lots of objects, and eventually will probably crash your PC. Each of the three sections of the for-loop is optional. Technically, you could even leave all three sections blank and provide only two semicolons. Be careful, though, because that way you would create a loop that would never terminate (an “infinite loop”).

While-Loop

Our second loop is the while-loop. A while-loop allows the code to repeatedly execute WHILE a boolean condition is met. The basic syntax for a while-loop is shown below:

while(condition) {

    //Code that executes if the condition is true

}

Example 3

The while-loop is useful when you have a condition that is being dynamically calculated. We could create the person object inside a while-loop, by dynamically changing the value of a variable ‘i’.

public void shouldReturnNumberOfPersonsInLoop() {

    Person person1;

    int i = 0;

    while (i < 4) {
        person1 = new Person();
        i++;
    }
    assertEquals(4, Person.numberOfPersons());
}

Example 4

In Example 4, we again create four person objects. Again, we start off with ‘i’ valued at 0 and increment it by 1 while ‘i<4’. When that condition becomes false and i’s value is 4, the loop is exited.

Do-while Loop

The third type of loop we’ll look at in this article is the do-while loop. A do-while loop executes the code at least once and then repeatedly executes the block based on a boolean condition. It functions like a while-loop after the first iteration, which happens automatically. In Example 6, we create the four Person objects using a do-while loop.

@Test
    public void shouldReturnNumberOfPersonsInLoop() {
        Person person1;
        int i = 0;
        do {
            person1 = new Person();
            i++;
        } while (i < 4);
        assertEquals(4, Person.numberOfPersons());
}

Example 5

There is also a fourth type of loop, the for-each loop. The loop you should choose depends on the logic you need. All four of the loops are equivalent in terms of functionality, but each loop expresses the logic in a different style. You should always try to use the loop that is easiest for someone reading your code to understand and that makes the most sense in context.

Thanks for reading!

Subscribe now to be informed when my Java Clean Code Video Course launches and to receive a 20% discount. You will also gain access to accompanying course material in the form of printable pdf's and receive another free Java tutorial after you have subscribed. Enter your email address to get these exclusive offers now.

I respect your privacy. I'll NEVER sell, rent or share your email address.
That's more than a policy, it's my personal guarantee!

Back to course page