Popular Searches
Popular Course Categories
Popular Courses

Using break, continue, and Labeled Statements

Using break, continue, and Labeled Statements

Loops and Iteration in Java

Using break, continue, and Labeled Statements in Java

Course: Core Java Training

Topic: Using break, continue, and Labeled Statements

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to break, continue, and Labeled Statements

Java provides several control-flow statements that allow programmers to change the normal execution of loops and other statements. The break and continue statements are particularly useful when working with repetitive operations, conditional processing, and nested loops.

The break statement terminates a loop or switch statement, while continue skips the remaining statements in the current loop iteration and proceeds toward the next iteration. Labeled statements allow programmers to identify a particular statement, enabling labeled break and continue operations to target an enclosing loop or statement.

These concepts are useful when searching arrays, skipping unwanted values, processing two-dimensional data, validating input, and controlling nested iterations.

Learning objectives

  • Understand the purpose of the break statement.
  • Learn how continue changes loop execution.
  • Understand labeled statements and their syntax.
  • Differentiate labeled break from labeled continue.
  • Use control-flow statements with for, while, and do-while loops.
  • Apply these statements to nested loops and searching algorithms.
  • Identify common errors and follow good programming practices.

2. Understanding the break Statement

The break statement immediately terminates the nearest enclosing loop or switch statement. After the statement is executed, control moves to the first statement following the terminated construct.

In Java, an unlabeled break is commonly used in:

  • for loops
  • while loops
  • do-while loops
  • switch statements

Syntax

break;

Example: Stop a loop at a specific value

public class BreakExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;
            }

            System.out.println(i);
        }

        System.out.println("Loop terminated");
    }
}

Output:

1
2
3
4
Loop terminated

Explanation: The loop begins at 1 and prints each value. When i becomes 5, the condition is true and break terminates the loop. The value 5 is not printed because the break statement executes before the print statement.

3. Using break with a while Loop

A break statement can stop a while loop when a particular condition occurs, even if the loop's original condition is still true.

public class WhileBreakExample {
    public static void main(String[] args) {
        int number = 1;

        while (number <= 10) {
            if (number == 4) {
                break;
            }

            System.out.println(number);
            number++;
        }
    }
}

Output:

1
2
3

Although the while condition permits values through 10, the break statement stops execution when the number reaches 4.

4. Using break with a do-while Loop

A break statement can also terminate a do-while loop. Remember that the do-while body normally executes before its continuation condition is checked, but break can exit the loop earlier.

public class DoWhileBreakExample {
    public static void main(String[] args) {
        int count = 1;

        do {
            if (count == 4) {
                break;
            }

            System.out.println(count);
            count++;
        } while (count <= 8);

        System.out.println("Finished");
    }
}

Output:

1
2
3
Finished

When count reaches 4, the loop terminates immediately without evaluating the do-while condition for that iteration.

5. Using break in a switch Statement

In a traditional switch statement, break prevents execution from falling through into subsequent case sections. It is commonly placed at the end of each case that should finish independently.

public class SwitchBreakExample {
    public static void main(String[] args) {
        int choice = 2;

        switch (choice) {
            case 1:
                System.out.println("Create");
                break;
            case 2:
                System.out.println("Update");
                break;
            case 3:
                System.out.println("Delete");
                break;
            default:
                System.out.println("Invalid choice");
        }
    }
}

Output:

Update

The break statement ends the switch after the matching case executes. Without it in traditional colon-style syntax, execution could continue into later case sections.

6. Practical Example: Searching an Array Using break

When searching an array, the program can stop as soon as it finds the required value. Continuing to search after finding the target is often unnecessary.

public class ArraySearch {
    public static void main(String[] args) {
        int[] numbers = {10, 25, 30, 45, 50};
        int target = 30;
        int index = -1;

        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                index = i;
                break;
            }
        }

        if (index != -1) {
            System.out.println("Value found at index: " + index);
        } else {
            System.out.println("Value not found");
        }
    }
}

Output:

Value found at index: 2

The loop stops as soon as it finds 30 at index 2. If the target does not exist, the loop completes normally and the index remains -1.

7. Understanding the continue Statement

The continue statement skips the remaining statements in the current iteration of a loop and proceeds to the next iteration. Unlike break, it does not terminate the entire loop.

The continue statement can be used in Java's for, while, and do-while loops. It cannot be used independently as a way to skip a switch case.

Syntax

continue;

Example: Skip a particular number

public class ContinueExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i == 3) {
                continue;
            }

            System.out.println(i);
        }
    }
}

Output:

1
2
4
5

When i equals 3, continue skips the print statement for that iteration. The loop then proceeds with the next iteration.

8. Using continue with a for Loop

In a traditional for loop, continue transfers control toward the update expression and then the condition check. This is useful when certain values should be ignored while the loop continues processing other values.

public class EvenNumbers {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i % 2 != 0) {
                continue;
            }

            System.out.println(i);
        }
    }
}

Output:

2
4
6
8
10

The condition i % 2 != 0 identifies odd numbers. When the condition is true, continue skips the print statement. Only even numbers are printed.

9. Using continue with a while Loop

When using continue in a while loop, ensure that any necessary update occurs before continue is reached. Otherwise, the loop may repeat forever.

public class WhileContinueExample {
    public static void main(String[] args) {
        int i = 0;

        while (i < 6) {
            i++;

            if (i == 3) {
                continue;
            }

            System.out.println(i);
        }
    }
}

Output:

1
2
4
5
6

The counter is incremented before the continue statement. Therefore, even when 3 is skipped, the loop progresses toward its stopping condition.

10. Using continue with a do-while Loop

In a do-while loop, continue transfers control to the condition check. If the condition is true, the next iteration begins.

public class DoWhileContinueExample {
    public static void main(String[] args) {
        int number = 0;

        do {
            number++;

            if (number == 3) {
                continue;
            }

            System.out.println(number);
        } while (number < 5);
    }
}

Output:

1
2
4
5

The number 3 is skipped. The counter is incremented before continue, so the loop still reaches its terminating condition.

11. Practical Example: Calculate the Sum of Positive Numbers

The continue statement can help ignore unwanted values when processing data. In the following example, negative values are skipped while non-negative values are added to a total.

public class PositiveSum {
    public static void main(String[] args) {
        int[] values = {10, -5, 20, -2, 15};
        int sum = 0;

        for (int value : values) {
            if (value < 0) {
                continue;
            }

            sum += value;
        }

        System.out.println("Sum of non-negative values: " + sum);
    }
}

Output:

Sum of non-negative values: 45

The negative values -5 and -2 are skipped. The values 10, 20, and 15 are added to produce 45.

12. What Are Labeled Statements?

A labeled statement is a Java statement preceded by an identifier followed by a colon. Labels can be used with labeled break and labeled continue statements to target a particular enclosing statement.

A label is not a general-purpose jump mechanism, and Java does not provide a goto statement. A label identifies the statement immediately following it, and a labeled control-flow statement can refer to that label when it is in scope.

Syntax

labelName:
    statement;

For example, a loop can be labeled like this:

outerLoop:
for (int i = 1; i <= 3; i++) {
    System.out.println(i);
}

The label outerLoop identifies the for statement. The label itself does not change the loop's behavior unless a labeled break or continue refers to it.

13. Why Are Labeled Statements Useful?

Labeled statements are especially useful when working with nested loops. Normally, an unlabeled break or continue affects only the innermost applicable loop. A labeled statement allows the program to target an enclosing loop explicitly.

  • Exit multiple nested loops when a target value is found.
  • Skip to the next iteration of an outer loop from inside an inner loop.
  • Simplify certain search operations in two-dimensional arrays.
  • Control nested iterations without adding extra Boolean flags in some situations.

Labels should be used carefully. If ordinary break, continue, or a well-structured method can solve the problem clearly, that approach may be easier to maintain.

14. Labeled break Statement

A labeled break terminates the labeled statement, which may be an enclosing loop or another labeled statement. Execution then continues after that labeled statement.

Syntax

break labelName;

Example: Exit an outer loop

public class LabeledBreakExample {
    public static void main(String[] args) {
        outerLoop:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                System.out.println("i = " + i + ", j = " + j);

                if (i == 2 && j == 2) {
                    break outerLoop;
                }
            }
        }

        System.out.println("Outer loop terminated");
    }
}

Output:

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
Outer loop terminated

When both i and j equal 2, break outerLoop; terminates the entire labeled outer loop. The inner loop does not simply continue with its next iteration.

15. Searching a Two-Dimensional Array with Labeled break

A two-dimensional array contains rows and columns. Searching every element can require nested loops. A labeled break allows the program to exit both loops immediately after finding the target.

public class MatrixSearch {
    public static void main(String[] args) {
        int[][] matrix = {
            {10, 20, 30},
            {40, 50, 60},
            {70, 80, 90}
        };

        int target = 50;
        int row = -1;
        int column = -1;

        search:
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == target) {
                    row = i;
                    column = j;
                    break search;
                }
            }
        }

        if (row != -1) {
            System.out.println("Found at row " + row
                    + ", column " + column);
        } else {
            System.out.println("Value not found");
        }
    }
}

Output:

Found at row 1, column 1

The target 50 is found at row 1 and column 1, using zero-based indexing. The labeled break immediately exits the labeled search loop.

16. Labeled continue Statement

A labeled continue skips the remainder of the current iteration of the specified enclosing loop and proceeds with that loop's next iteration. Unlike labeled break, it does not terminate the target loop entirely.

Syntax

continue labelName;

Example: Skip an outer-loop iteration

public class LabeledContinueExample {
    public static void main(String[] args) {
        outerLoop:
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    continue outerLoop;
                }

                System.out.println("i = " + i + ", j = " + j);
            }
        }
    }
}

Output:

i = 1, j = 1
i = 2, j = 1
i = 3, j = 1

When j becomes 2, continue outerLoop; ends the current iteration of the outer loop. The outer loop proceeds to its next iteration, and the inner loop starts again. Consequently, the statement for j = 2 is skipped for every outer iteration.

17. Difference Between break, continue, and Labeled Statements

Feature break continue Labeled break / continue
Main purpose Terminate a loop or switch Skip the current loop iteration Target a specified enclosing statement or loop
Effect on the loop Exits the targeted construct Starts the next iteration Depends on whether break or continue is used
Default target Nearest enclosing loop or switch Nearest enclosing loop Enclosing statement with the matching label
Common application Stop when a value is found Skip unwanted values Control nested loops
Example break; continue; break search;

18. Labeled break vs. Labeled continue

Although both statements use a label, their effects are different.

  • Labeled break: Exits the labeled statement completely and continues after it.
  • Labeled continue: Ends the current iteration of the labeled loop and proceeds to its next iteration.

A labeled continue must target an enclosing iteration statement such as a for, while, or do-while loop. A labeled break can target an enclosing labeled statement more generally, including a labeled block.

19. Labeled Statements with a Block

Java labels can identify a block of statements as well as a loop. A labeled break can exit that block. This is sometimes useful when several operations should be abandoned together, although methods or other structured control flow may provide a clearer alternative.

public class LabeledBlockExample {
    public static void main(String[] args) {
        process:
        {
            System.out.println("Step 1");

            if (true) {
                break process;
            }

            System.out.println("Step 2");
        }

        System.out.println("After the block");
    }
}

Output:

Step 1
After the block

The labeled break exits the block named process. It does not jump to the label itself; execution continues with the statement immediately after the labeled block.

20. Common Mistakes and Errors

  • Confusing break and continue: Break terminates the targeted construct, while continue skips to the next iteration.
  • Using continue outside a loop: Continue must target an enclosing for, while, or do-while loop.
  • Using a nonexistent label: The label referenced by a labeled break or continue must be in scope.
  • Targeting the wrong loop: A label may refer to an outer loop when the programmer intended to affect only the inner loop.
  • Forgetting the loop update: Using continue before updating a while-loop counter can cause an infinite loop.
  • Assuming break always exits every loop: An unlabeled break exits only the nearest enclosing loop or switch.
  • Using labels unnecessarily: Excessive labels can make code harder to follow.
  • Misreading labeled continue: It does not terminate the labeled loop; it continues with that loop's next iteration.
  • Incorrect label placement: A label identifies the statement immediately following it, so the intended loop or block must be labeled.

21. Best Practices

  • Use break when the program has found the required value or has reached a clear stopping point.
  • Use continue when a particular value should be skipped while processing continues.
  • Use labeled statements mainly when nested-loop control genuinely requires them.
  • Choose meaningful labels such as search, outerLoop, or rowLoop.
  • Keep nested loops and their exit conditions as simple as possible.
  • Update counters before continue when required to ensure the loop makes progress.
  • Test cases where the target value is found early, found late, or not found.
  • Use comments to explain non-obvious labeled break or continue behavior.
  • Consider extracting complicated logic into a separate method if that improves readability.
  • Review each control-flow path to ensure the program produces the expected output.

22. Practice Exercises

Exercise 1: Stop at a Number

Write a for loop that prints numbers from 1 to 20 but stops when the value reaches 12 using break.

Exercise 2: Skip Odd Numbers

Use continue to print only even numbers from 1 to 30.

Exercise 3: Search an Array

Create an integer array and search for a target value. Use break to stop when the target is found.

Exercise 4: Nested Loop Exit

Create two nested loops and use a labeled break to exit both loops when a specified combination of row and column values occurs.

Exercise 5: Labeled Continue

Write nested loops that use labeled continue to skip an outer-loop iteration when an inner-loop condition is met.

Exercise 6: Skip Negative Values

Given an array containing positive and negative numbers, use continue to ignore negative values and calculate the sum of the remaining values.

Exercise 7: Matrix Search

Search for a number in a two-dimensional array. Print its row and column indices and use labeled break to stop searching.

Exercise 8: Labeled Block

Create a labeled block with three print statements. Use a labeled break to skip the last statement and observe the output.

23. Interview Questions and Answers

Q1. What is the break statement in Java?

The break statement terminates the nearest enclosing loop or switch statement. A labeled break can terminate a specified enclosing labeled statement.

Q2. What is the continue statement?

Continue skips the remainder of the current iteration of a loop and proceeds toward the next iteration.

Q3. Can break be used in a switch statement?

Yes. In a traditional switch statement, break is commonly used to prevent execution from falling through into subsequent case sections.

Q4. Can continue be used in a switch statement?

Continue cannot target a switch by itself. It can appear inside a switch that is nested within a loop, provided it targets an enclosing loop.

Q5. What is a labeled statement?

A labeled statement is a statement preceded by a label identifier and a colon. The label can be referenced by a labeled break or continue when the target is in scope.

Q6. What is the difference between labeled break and labeled continue?

Labeled break exits the specified labeled statement. Labeled continue skips the current iteration of the specified enclosing loop and proceeds to its next iteration.

Q7. Why are labeled statements useful in nested loops?

They allow a programmer to exit an outer loop or continue an outer-loop iteration directly from within an inner loop.

Q8. Does an unlabeled break exit all nested loops?

No. An unlabeled break exits only the nearest enclosing loop or switch. Use a labeled break if an outer loop must also be terminated.

Q9. Can a labeled break exit a block?

Yes. A labeled break can exit an enclosing labeled block as well as a labeled loop or switch statement.

Q10. What problem can occur when continue is used in a while loop?

If continue skips the code responsible for updating the loop-control variable, the condition may remain true indefinitely, creating an infinite loop.

24. Quick Revision Checklist

  • Understand the difference between break and continue.
  • Know that unlabeled break exits the nearest loop or switch.
  • Know that continue targets a loop, not a switch by itself.
  • Understand the syntax and purpose of labels.
  • Differentiate labeled break from labeled continue.
  • Practice searching arrays and two-dimensional arrays.
  • Check counter updates when using continue.
  • Use labels only when they improve nested-loop control.
  • Test all relevant control-flow paths.

25. Conclusion

The break, continue, and labeled statement features give Java programmers greater control over loops and conditional execution. Break is useful for stopping a loop or switch, continue is useful for skipping unwanted iterations, and labeled break or continue can target an enclosing statement in nested-loop situations.

Understanding these control-flow statements helps you write more efficient search operations, array-processing programs, and nested-loop algorithms. Use them carefully, keep the logic readable, and practice with small programs before applying them to more complex applications.

Continue learning with JustAcademy: Explore the Core Java Training Course, register for a course demo, or visit the JustAcademy homepage.

Official Java reference: Oracle Java Tutorial: Branching Statements.

whatsapp