Continue and break, with and without labels, for the SCJP

Looping constructs are very useful in any programming language, however they can be come particularly complex when you have a variety of nested loops and you need to drop out from particular iterations, or exit the loops entirely under a set of given circumstances. Fortunately for us, Java provides us with 2 keywords that we can use to help in these situations:

  • break – breaks out of the entire loop, and no more iterations will occur. The thread of execution will then move onto the next line of code after the loop.
  • continue – the current iteration will be terminated, and the thread of execution will move onto the next iteration, if there is one, otherwise the loop will complete.

It is important to note, that in both of these keywords, unless otherwise specified via the use of a label, they will apply to the inner most loop that is currently executing.

If you would like to break or continue out of a loop that happens to be nested outside of your current loop, then you need to use labeled loops, whereby you give each one a label and then you can continue/break on one of those given labels. For example, if you have 3 loops, one nested in another, and you’re cycling through the inner most loop and decide that you don’t need to iterate over any of them anymore, as you have all the data you need, then you can call break on the outermost loop and move onto the next piece of code.

Please consider the following example that I have on my SCJP examples page, if I’ve missed anything obvious please let me know:

package com.jameselsey.demo.scjp.flow_control;

/**
 * Author:  JElsey
 * Date:    22/08/2012
 *
 * Experimenting with the break and continue keywords, also using labeling.
 */
public class UsingBreakAndContinue
{
    public static void main(String[] args)
    {
        doUnlabeledBreak();
        doUnlabeledContinue();

        doLabeledBreak();
        doLabeledContinue();

        doNestedLabeledBreak();
        doNestedLabeledContinue();
    }

    /*
        Since we're not using any labels here, the break will break out of the inner most loop, then move
        onto the next statement AFTER the loop. Break will "break out" immediately from the iteration, great for
        cases when you're counting up something, find you have done all the iterations you need, then you can break out
        and prevent wasting time on iterations you no longer need.
     */
    private static void doUnlabeledBreak()
    {
        System.out.println("START - Un-labeled break");
        for (int i = 0; i < 5; i++)
        {
            System.out.println("\tIteration on i:" + i);
            System.out.println("\tLets call break, we don't want to do any more");
            break;
            // We're done with the whole loop, "break out" and move onto whatever comes after the loop
            // we don't want to do any more iterations
        }
        System.out.println("END - Un-labeled break");

    }

    /*
        We're using no labeling here, so much like the example above, the continue will take effect on the inner most
        loop. Continue drops out of the current iteration immediately, and attempts the next iteration, if there is one.
        This is great for scenarios where you're checking numbers for odd/even, if its an odd number, you could continue on
        to the next iteration; if you only require doing stuff with even numbers (just an example).
     */
    private static void doUnlabeledContinue()
    {
        System.out.println("START - Un-labeled continue");
        for (int i = 0; i < 5; i++)
        {
            System.out.println("\tIteration on i:" + i);
            System.out.println("\tLets call continue, we don't want to do any more in this iteration");
            continue;
            // anything under here can't be accessed, since you've called continue which drops out
            // of the iteration and "continues" with the next iteration, if there is one
        }
        System.out.println("END - Un-labeled continue");
    }

    /*
        Behaves similar to the unlabeled break, however if you break on a label, it will break for THAT label rather
        than the inner most loop. This is great when you have complex, nested iteration cycles.
     */
    private static void doLabeledBreak()
    {
        System.out.println("START - labeled break");
        labeledBreak:
        for (int i = 0; i < 5; i++)
        {
            System.out.println("\tIteration on i: " + i);
            System.out.println("\tLets call break, we don't want to do any more in this iteration");
            break labeledBreak;
            // We've broken out to the "labeledBreak", so we won't do any more further iterations of this label
        }
        System.out.println("END - labeled break");
    }

    /*
        Similar to the labled break, the labeled continue will move onto the next iteration of the label you've
        specified, if there is an iteration, otherwise the loop is complete.
     */
    private static void doLabeledContinue()
    {
        System.out.println("START - Labeled continue");
        labeledContinue:
        for (int i = 0; i < 5; i++)
        {
            System.out.println("\tIteration on i:" + i);
            System.out.println("\tLets call continue, we don't want to do any more in this iteration");
            continue labeledContinue;
            // anything under here can't be accessed, since you've called continue which drops out
            // of the iteration and "continues" with the next iteration, if there is one
        }
        System.out.println("END - Labeled continue");
    }

    /*
        Using nested breaks here, with labels, so you can see how breaking out of individual nested looping
        constructs would work.
     */
    private static void doNestedLabeledBreak()
    {
        System.out.println("START - Nested Labeled break");
        outerLoop:
        for (int i = 0; i < 5; i++)
        {
            innerLoop:
            for(int inner = 0; inner < 5; inner++)
            {
                System.out.println("We're in the inner loop, lets break out of it...");
                break innerLoop;
            }
            System.out.println("Now lets break out of the outer loop too");
            break outerLoop;
        }
        System.out.println("END - Nested Labeled break");
    }

    /*
        Using nested labeled continues here to demonstrate how you'd continue onto labeled looping constructs.
     */
    private static void doNestedLabeledContinue()
    {
        System.out.println("START - Nested Labeled continue");
        outerLoop:
        for (int i = 0; i < 5; i++)
        {
            innerLoop:
            for(int inner = 0; inner < 5; inner++)
            {
                System.out.println("We're in the inner loop, lets continue out of it...");
                continue innerLoop;
            }
            System.out.println("Now lets continue out of the outer loop too");
            continue outerLoop;
        }
        System.out.println("END - Nested Labeled continue");
    }

    /*
        Not quite sure where I was going with this one, but was experimenting with some continue
        and break combinations.
     */
    private static void countingNumbers()
    {
        outerLoop:
        for(int i = 0; i         {
            if(i % 2 == 0)
            {
                System.out.println("Number is odd, lets continue to next iteration");
                continue outerLoop;
            }

            int sumOfEvens = 0;
            for(int j = 0; j < i; j++)
            {
                 sumOfEvens+= j;
            }

            if(i == 50)
            {
                System.out.println("We'll only count halfway, and give up at 50");
                break outerLoop;
            }
        }
    }
}

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!

Java; the for-each loop, perfect for fondling collections and arrays

The for loop is great, but is it really that nice when you want to iterate over an array or collection? You’d have to do something like the following :

import java.util.ArrayList;
import java.util.List;

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        List<String> myList = new ArrayList<String>();
        myList.add("Hello");
        myList.add("James");
        myList.add("Elsey");

        for (int i = 0; i < myList.size(); i++)
        {
            System.out.println(myList.get(i));
        }
    }
}

Works fine doesn’t it? Looks a bit messy doesn’t it? No need for the index since we only ever use it to get the current value out of the list. Lets have a look at the for-each loop (often called the enhanced for loop) and how it can help

for (String s : myStrings)
{
   // do stuff with "s"
}

Essentially, what the for each loop does, is allow you to loop through each item in the collection or array. The above example, in plain English means : “for each String in myStrings, assign it to s and do something with it”.

Now lets look at a real example

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        List<String> myList = new ArrayList<String>();
        myList.add("Hello");
        myList.add("James");
        myList.add("Elsey");

        for (String s : myList)
        {
            System.out.println(s);
        }
    }
}

Thats great! How much cleaner and easier to read is that?! Since there is no boolean expression involved with this type of looping, it is always assumed that the loop will iterate through every item in the array or collection.

Lets have a look at another few examples to get your understanding up to scratch

import java.util.ArrayList;
import java.util.List;

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        List<String> myList = new ArrayList<String>();
        myList.add("Hello");
        myList.add("James");
        myList.add("Elsey");
        for (String s : myList)
        {
            System.out.println(s);
        }
        
        char[] myChars = new char[]{'a','b','c'};
        for (char c : myChars)
        {
            System.out.println("char is : " + c);
        }
        
        int[] myInts = new int[]{1,2,3,4};
        for (int i : myInts)
        {
            System.out.println("int is : " + i);   
        }
    }
}

I hope I’ve explained it well, if I can improve, please let me know!

Happy looping!

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.

Using while loops, for when you don’t know how long the piece of string is…

Just another bitesize SCJP post here, looking at the while loop in Java.

There may be times, where you need to continually iterate over a code block for an unknown number of times. What you can do, is to loop through a code block while a condition is true, something else might change that condition, and when this happens, you can exit out of the loop.

In a psuedo-code way, this is how the while loop operates :

while (boolean_expression)
{
  //do stuff here
}

The boolean_expression, as the name suggests must equal a boolean value. All of the following examples are valid

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        int x = 2;
        while (x == 2)
        {
            System.out.println("Inside the loop!");
            x = 3;
        }

        String myString = "James";
        while (myString.equals("James"))
        {
            System.out.println("Inside the loop!");
            myString = "Elsey";
        }

        while (3 > 2)
        {
            System.out.println("You'll only see this once, then we'll break out of the loop");
            break;
        }

        while (true)
        {
            System.out.println("You'll only see this once, then we'll break out of the loop");
            break;
        }

        System.out.println("Done with our looping samples");
    }
}

For the first 2 examples, we check to see if a variable is a certain value, if that is true (in which it is) then we drop into the loop and print out a value. For the first 2 examples, during the first iteration we actually modify that variable, so when the loop ends and we re-check the boolean expression it now evaluates to true, so we don’t drop in for another iteration.

The last 2 examples can be considered as continual, or never-ending loops, since the evaluates will always be true. For example, 3 will always be greater than 2, nothing except the laws of physics and maths can ever change that, true will always be true, always! This means that the loop will continually iterate over and over again, until the end of time or when you pull the plug. The only way to get out of this type of loop is to use the break keyword, this essentially bails out of the loop.

Lets have a look at one more example :

public class MonkeySniffer
{
public static void main(String[] args)
{
int x = 0;
while (x < 10)
{
System.out.println("Inside the loop!");
x++;
}
}
}

This behaviour is very similar to that of the standard for loop, a condition is met and the loop is entered, until that condition can no longer be met.

To be honest, there is very little to the while loop, so I think I’ve covered it all here! If theres anything I’ve missed, please leave me some comments!

Happy coding.,

Playing with the For loop in Java…

The for loop is an extremely flexible and powerful way of iterating over a code block for a set number of times. Generally speaking, this type of loop is great for situations when you need to repeat code for a definitive number of times, for example you know that your shopping basket contains 10 items, so you need to repeat the loop body 10 times, to iterate through each item and print it onto the screen.

In order to use this loop, you must first create the for loop, and then specify the code block that is used for iteration. Lets take a look at a brief bit of psuedo code.

for(initialization; Boolean_expression; update)
{
   //Statements
}

So there are 3 things that happen inside the for loop delcaration, lets have a look at those too.

  • Initialisation – This is where you can setup any control variables for the loop, normally you would set up an int to hold the position you have in the loop. Technically this part isn’t required, you can just leave it blank, but most of the time you would use it.
  • Boolean expression – This boolean expression is evaluated before each cycle of the loop to determine if another iteration should be performed. Before the body of the loop is executed, this expression is evaluated, if it equals true, then the loop body executes, if it is false, then it goes to the next line of code after the loop body.
  • Update – After the body of the loop has execute, the update section will occur. This allows you to update any of the control variables that were setup in the initialisation block. This part isn’t mandatory, so you could just leave the semi colon.

Enough talk, lets actually have a look at a real life for loop.

public class MonkeySniffer
{
    public static void main(String[] args)
    {
         for (int i = 0; i < 10; i++)
         {
             System.out.println(i);
         }
         System.out.println("Done with the loop");
    }
}

Just before we get into what actually happens, you might be thinking that the “for” line looks a little complex, so how do you know where the initialisation ends and the boolean expression starts? Easy, look for the semi-colon. The semi-colon is the delimiter between the 3 sections.

So lets think about this above example a little more. We can see that during the initialisation block we create a new int called i, and assign it the value of 0. Thats our control variable. Next the boolean expression, before each iteration of the loop we will check to make sure that i is smaller than 10. If i is less than 10, we’ll run the loop body, otherwise we’ll continue to the next line of code after the loop. Since we have just initialised i to be 0, it is of course less than 10 so we run the code body.

The code body will simply output the value of i to the system console. After the code body is complete, we run the update section of the loop, in this case we increment i. At this stage i would then become 1.

That is just one iteration, we then attempt another. Remember from earlier, that we only run the initialisation once. We do this only once, otherwise we would then reset i back to 0 and the loop would never get anywhere. So for the second iteration we evaluate the expression again, in our case we just set i to be 1, so it still matches the expression, and we continue into the code body.

This happens over and over again, until we get to a stage where i isn’t smaller than 10, its actually 11. The boolean expression fails, so we don’t enter the loop body, we’re done, finished, fín, finito. We move onto the next line, being a print of “Done with the loop”.

Lets have a look at another example, this time we’ll count downwards instead of upwards :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        for (int i = 10; i > 0; i--)
        {
            System.out.println(i);
        }
        System.out.println("Done with the loop");
    }
}

This time, we start off “i” as 10. Then we loop through while “i” is greater than 0. After each iteration we decrement i by 1. So in plain English, we start off at 10, and count downwards by 1 until we reach 0.

Getting the hang of it? Well lets throw some gas on the fire, and count both ways, at the same time :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        for (int i = 0, j = 10; i < 10 && j > 0; i++, j--)
        {
            System.out.println("i is " + i + " and j is " + j);
        }
        System.out.println("Done with the loop");
    }
}

So what we are doing here, is setting up i as 0, and j as 10. Then while both i is less than 10, and j is greater than 0, continue with the loop. After each iteration, increment i, and decrement j. During each iteration we print out the current value of i and j.

Avoid the continuous loop..

As I said earlier in the post, the statements inside the for loop declaration are not mandatory, you could choose not to provide them. Since you don’t provide a boolean expression, the loop will never know when to exit, so will continue over and over again, have a look at the following :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        for (;;)
        {
            System.out.println("Someone make me a cup of tea!");
        }
        // the below is unreachable, since the above is a continuous loop
        // System.out.println("Done with the loop");
    }
}

Of course, its not very pretty, but it does the job. There may be times when you do need to keep repeating something continuosly, but personally the following option is far cleaner :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        while (true)
        {
            System.out.println("Someone make me a cup of tea!");
        }
        // the below is unreachable, since the above is a continuous loop
        // System.out.println("Done with the loop");
    }
}

Further Reading
Oracle Tutorial on the for loop