Skip to main content

Control Flow

break and continue in Java

The "break" statement is like a stop sign for a loop in programming. Imagine you're counting numbers using a loop, and you want to stop the counting when a certain condition is met. That's when you use "break."  And the "continue" statement allows us to skip statements inside the loop.

let's talk about break and continue in a way that's easy to understand.

Imagine you're making a list of tasks, like washing dishes. A loop is like going through each dish one by one.

Break:

Sometimes, you might need to stop doing the dishes before finishing them all. "Break" is like saying, "Okay, I'm done for now." It lets you leave the kitchen right away, even if there are more dishes.

For example:

for (int i = 1; i <= 5; ++i) {
    System.out.println("Washing dish number " + i);
    if (i == 3) {
        break; // Stop washing dishes after the 3rd one
    }
}
System.out.println("Done with the dishes (outside the loop).");

Output

Washing dish number 1
Washing dish number 2
Washing dish number 3
Done with the dishes (outside the loop).

Here, the loop should iterate 5 times from i equals 1 to 5. However, after printing 3, the value of i, the if condition is satisfied andbreak statement is encountered and the loop terminates.

In most cases, we want to terminate the loop in the middle only when a specific condition is met. That's why the break statement is almost always used inside an if statement. So, in plain language, "break" is like telling yourself, "I'm done after this specific task."

Continue:

Now, let's say some dishes are super easy, and you don't want to spend much time on them. "Continue" helps with that. It's like saying, "I'm skipping this one quickly."

For example:

for (int i = 1; i <= 5; ++i) {
    if (i == 2 || i == 4) {
        continue; // Skip washing dishes number 2 and 4
    }
    System.out.println("Washing dish number " + i);
}
System.out.println("Done with the dishes (outside the loop).");

Output

Washing dish number 1
Washing dish number 3
Washing dish number 5
Done with the dishes (outside the loop).

In simple terms, "continue" is your way of saying, "I don't want to spend much time on this one, let's move on."

So, "break" helps you leave the kitchen early, and "continue" helps you breeze through some tasks without getting stuck on them. They're like your helpers in managing your to-do list!

Practice problem

Create a program to calculate the sum of integers entered by the user until the user enters 0 or negative integer. Initialise a variable named total with value 0 at the beginning.

Note: The negative number shouldn't be added to the totalvariable.

Hint
Create a while loop with condition true.
If the user enters 0 or negative integer, use break to terminate the loop.
If the user enters a positive number, add it to the total variable.
Print the total from outside of the loop.
Solution Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int num;

        int total = 0;
        // Continue looping until the user enters 0 or a negative integer
        while (true) {
            // Get an integer input from the user
            System.out.print("Enter an integer (0 or negative to exit): ");
            num = input.nextInt();

            // Check if the input is 0 or negative, and break the loop if true
            if (num <= 0) {
                break;
            }

            // Add the value to the total
            total += num;
        }

        // Print the total sum
        System.out.println("Total sum: " + total);
    }
}

Write a program that takes a positive integer, n, as input from the user. The program should then print all the odd numbers between 1 and n.

Note: We assume that the user will always provide a positive integer.

Follow these steps
Request the user to input a positive integer and store it in a variable named n.
Use a loop to iterate from 1 to n.
Inside the loop:
If the current number i is even, use "continue" to skip it from printing.
If the current number i is odd, print its value.
Solution Code
import java.util.Scanner;

public class OddNumbersPrinter {
    public static void main(String[] args) {
        // Create a Scanner object to read input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a positive integer
        System.out.print("Enter a positive integer (n): ");
        
        // Read the user input
        int n = scanner.nextInt();

        // Print all odd numbers between 1 and n
        System.out.println("Odd numbers between 1 and " + n + ":");
        for (int i = 1; i <= n; i++) {
            if(i%2 == 0)
              continue;
            System.out.println(i);
        }
    }
}