Lesson 6 – Loops

Ok, In the last lesson we learnt how to use Methods, pass parameters to them and get return values. But what if we want to call something many times consecutively.

The programming you have done so far in this lesson series is known as ‘sequential programming’. Sequential programming means that the code has executed from the top of the class to bottom. Each line of code will be read and fulfilled in a sequential order.

In the next few lessons of the series, we are going to show you that code can be executed only if certain ‘conditions’ are met. First, we’ll look at loops and in the next lesson conditional statements.

Downloads

To get started you can use the basic starter project and follow the steps to compile the code examples for the lesson.

There are three main loops we can use in Java:

  • while
  • do while
  • for

Since Java version 5, we also have the ‘enhanced’ version of the for loop. We’ll be covering each loop in this lesson and when to use them. Let’s get started.

The Stupid Way

Ok, Let’s have a look at something you have already learnt in previous lessons and how we can improve upon it using loops. Have a look at the following code:

So fairly basic right. Create a class called ‘Loops’, copy this into your starter project, create a main method and run the code to view its output.

So there’s nothing particularly wrong with this, but what if we wanted to print a thousand numbers? The code would get long and unreadable to say the very least. Thankfully there’s a way to tell java to stop executing sequentially (one line after another, always downwards until the end) and instead perform the same section of code more than once. This is the powerful concept of a loop.

The While Loop

The first loop in this lesson is the while loop. The while loop reads in plain English as:

While some expression is true; execute the code inside the loop. Then recheck the expression.

Let’s see an example:

Ok as usual try it out, copy the method into your Loops class and make sure to call it from your main method. You should notice that when you run the code, you get the same output as the previous code example.

So whats happening? Let’s take it step by step:

  1. When the code is called, i is created and initialized with a value of 1.
  2. The code then goes to the while expression and says: if i (i equals 1) is less than 4 return true
  3. The expression is true so we go inside the loop and i is printed
  4. i is then incremented by 1 (i now equals 2) and the code jumps back up to the while expression
  5. This time i is still less than 4 so again i is printed and incremented by 1
  6. This continues in a loop until i = 4
  7. The while expression is evaluated one more time. i (4) < 4 now gives a result of false, since 4 is not less than 4. The loop finishes without printing again and moves on downwards.

Try changing the number 4 inside the while expression and run the code. Note the larger the number is, the longer the code will take to execute. This is due to the number of cycles the loop will go through until the code reaches its end.

Another While Loop

Ok, we’re going to have a look at another while loop. This time we are going to use our knowledge of methods and their ability to take in parameters. In this case, the parameter is going to be the number of times the loop is to be executed:

Copy the code, call it from your main method and run it. To call the code, you’ll need to call the method and pass a value for the maxValue:

This parameterised version of the method is now much more useful to us as we can call the same code as before but with different results depending on how many times we loop through the code. Real life applications could be adding charges to someones account based on how many days late they have returned a book. Or calculating compound interest over x number of months. The possibilities here are endless.

Ok, let’s move on.

The Do … While Loop

Time to look at the do while loop. This loop is very similar to the while loop. Let’s look at the syntax and see if you can see what the difference is:

So there is a clear difference regarding the syntax of the Do loop. But the actual difference between these loops is a bit more subtle. Notice the While condition is at the end of the code block. This means the code is executed once before we evaluate whether i < 4. If i equalled 5, for example, the code would print 5 before deciding not to loop. Try it for yourself!

The For Loop

Ok, next up its the for loop. Let’s check it out:

Copy the code, run it, etc. The first thing most people will think is whats the difference!? We used a while loop to do the same thing just a few minutes ago. And your right to believe that, there are ways to implement either loop and obtain the same results.

In general, however, we use this rule of thumb to decide which loop to use: For loops are used when you know how many times you need to loop. While loops are used to loop until an event occurs. So use a for loop if you always want to loop 100 times. And, a while loop if you want to loop until some condition or event occurs (i.e. i is no longer less than some number).

The enhanced For Loop

Let’s take a very brief look at the enhanced loop. We’re not going to go into much detail into this loop as it covers ‘Collections’ which is something we will learn about in our intermediate course. But let’s just be aware of this loop and its syntax:

So in this method, we have created a Collection called an ArrayList. In this case, it is a list of Integers, but it can hold any type. The last few lines of the method is our enhanced for loop. This loop is capable of looping (or iterating) through each item (x) in our collection (array). We will use this more in the collections lessons.

Menu