Looping in Java, a brief look at the various loops and how they can be applied

One of the great features of any programming language is the ability to repeat blocks of code, sometimes indefinately, sometimes until a certain condition is met, or for a set number of iterations.

Luckily, Java comes with several flavours of loops, let have a brief look at our options

  • The “for” loop – The for loop is generally used when you know in advance how many iterations the loop must execute. The for loop enables you to setup a repeatable code block with access to the index(es)
  • The “for-each” loop (also known as the enhanced for loop) – Introduced in Java 5, the enhanced for loop is primarily used for iterating through arrays
  • The “while” loop – A boolean expression is evaluated, if the outcome is true, then the code in the following block will be executed, and the expression will be evaluated again. This cycle will continue until the expression evaluates to false.
  • The “do-while” loop – This loop is very similar to the while loop. However, one drawback of the while loop is that it will only execute if the expression evaluates to true. What if you wanted to run the iteration always once to begin with, and then start checking for further iterations? Well we have some news, the do-while loop saves the day.

I’ve linked each of the above into a separate post, please have a look at those, I’ve tried to explain it as much as I can in accordance to the SCJP exam guidelines.

Happy coding!

The do-while loop, always executes at least once…

As I’ve covered in a previous post regarding the while loop, the do-while, often refered to as the do loop is very similar. Lets have a look at the psuedo code.

do
{
    //do stuff in here
}
while (boolean_expression);

So as we can see, the actual body of the loop gets executed at least once before the boolean expression is ever evaluated. Now lets have a look at a real example :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        do
        {
            System.out.println("Inside the loop!");
        }
        while (3 > 4);
    }
}

What the above does, is to print out Inside the loop! once, then it checks the boolean expression in the while statement, if it is true then the loop will be repeated, if it is false, in this case it will be since 3 is not greater than 4, then the loop is done and the code will continue.

Thats it really, nothing too fancy here, this loop is really suited to situations where you must do something at least once, but possibly multiple times.

Anything I’ve missed please let me know!

Happy coding.