Chapter Table of Contents

Ch. 8 Loops

Section Table of Contents

Sometimes when we’re writing code for a loop, we’ll realize that there is a certain case that we might want to skip, or maybe there’s a case that should cause the loop to be terminated prematurely. To do this, we can use continue and break, respectively.

The continue keyword tells the program to skip to the next iteration. On the other hand, the break keyword tells the program to stop the loop completely.

Analyze the program below. What will the output be?

// *Testing the continue keyword*
        System.out.println("Testing continue");

        int sum = 0;
        int number = 0;

        // *Print the current number from 1-10,*
        // *but skip 7 and 8.*
        // *Also keep a running sum of the numbers.*
        while (number < 10) {
            number++;
            if (number == 7 || number == 8) {
                continue;
            }
            sum += number;
            System.out.printf("number: %d sum: %d.\\n", number, sum);
        }

        System.out.println("The sum is " + sum);

        // *Testing the break keyword*
        System.out.println("\\n\\nTesting break");

        sum = 0;
        number = 0;

        // *Print the current number from 1-6.*
        // *Also keep a running sum of the numbers.*
        while (number < 10) {
            number++;
            if (number == 7) { // *will never reach 8*
                break;
            }
            sum += number; // *7 is never added to the sum*
            System.out.printf("number: %d sum: %d.\\n", number, sum);
        }

        System.out.println("The sum is " + sum);

<aside> ⚠️ Note: This example program uses String formatting. If you are unfamiliar with this, you can read about it here.

</aside>

Output:

Testing continue
number: 1 sum: 1.
number: 2 sum: 3.
number: 3 sum: 6.
number: 4 sum: 10.
number: 5 sum: 15.
number: 6 sum: 21.
number: 9 sum: 30.
number: 10 sum: 40.
The sum is 40

Testing break
number: 1 sum: 1.
number: 2 sum: 3.
number: 3 sum: 6.
number: 4 sum: 10.
number: 5 sum: 15.
number: 6 sum: 21.
The sum is 21

Let’s break down this example. In the first part, we are testing the continue keyword. Notice that in the output, after number: 6 sum: 21, we go straight to number: 9 sum: 30. This is because in the while loop, if number is 7 or 8, we continue the loop and skip the code inside of the loop that is after the continue statement.

In the second part, we are testing the break keyword. Notice that in the output, after number: 6 sum: 21, the loop terminates right away. This is because if number is 7, the break statement is executed, which exits the loop completely.

<aside> 💡 Note: You can also use continue and break in a for loop or a do-while loop.

</aside>

💻 BreakVsContinue.java