Java - Break and Continue Statements

Break and Continue Statements in Java

Java provides several powerful control flow statements that help developers manage how loops and conditional structures behave. Among these, the break statement and the continue statement are two of the most frequently used control flow tools in Java programming. These statements help programmers control loop execution, stop iterations, skip steps, and create more optimized and readable code. This detailed HTML document explains Java break and continue statements with meaning, syntax, real-life use cases, complete Java programs, and outputs. Every concept is explained in 10–15 lines for clarity and SEO-rich understanding.

Introduction to Jump Statements in Java

Jump statements in Java allow the flow of program execution to jump from one point to another. They are essential for controlling loops, decision-making, and enhancing efficiency. Break and continue statements fall under this category. A jump statement helps terminate loops, skip iterations, leave switch blocks, and alter the normal execution of a program. These keywords make Java programs cleaner and more flexible. They reduce the need for complex conditional structures and help developers handle real-time scenarios like searching, filtering, and validating data.

Java Break Statement

What Is the Break Statement in Java?

The break statement in Java is a jump statement used to immediately terminate the execution of a loop or a switch block. When Java encounters a break statement inside a loop, the loop stops running instantly, and control moves to the next statement after the loop. It is widely used in situations where continuing the loop is unnecessary or inefficient. The break statement enhances performance by avoiding unnecessary iterations. It is particularly useful in searching algorithms, menu-driven programs, infinite loops, and nested loops. Understanding break is crucial for writing efficient and optimized Java programs.

Syntax of Break Statement

The syntax of the break statement is very simple and consists of a single keyword. It does not require parentheses, conditions, or expressions. In normal usage, break is included inside a loop or a switch case. When executed, it stops the nearest loop or switch block. The simplicity of its syntax makes it easy to integrate into any Java program. Break can also be used with labels, allowing developers to terminate specific loops within nested loops. The general syntax is shown below:


break;

Example 1 – Basic Break Statement in a For Loop

Below is a simple Java program demonstrating how the break statement works inside a for loop. The loop is designed to print values from 1 to 10, but when the value reaches 5, a break statement is triggered. This stops the loop immediately, and no further iterations are executed. This example helps beginners clearly understand how break interrupts loop execution.


public class BreakExample1 {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                break;
            }
            System.out.println("Value: " + i);
        }
    }
}

Output:


Value: 1
Value: 2
Value: 3
Value: 4

Example 2 – Break Statement in a While Loop

This example shows how break operates inside a while loop. A counter variable is incremented in each iteration. When the counter reaches 7, the break statement executes, stopping the loop immediately. This demonstrates that break works in all Java loops, not just for loops. It also helps understand how break can control infinite loops by manually terminating them at specific conditions.


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

        while (i <= 10) {
            System.out.println("Number: " + i);

            if (i == 7) {
                break;
            }
            i++;
        }
    }
}

Output:


Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7

Example 3 – Break Statement in Do-While Loop

The break statement works similarly in a do-while loop. The loop runs at least once, and upon reaching a specific condition, the break statement stops the loop. This example prints numbers from 1 to 5, and when the number becomes 3, the break keyword ends the loop. This helps illustrate how break is used across all loop structures in Java.


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

        do {
            System.out.println("i = " + i);

            if (i == 3) {
                break;
            }
            i++;
        } while (i <= 5);
    }
}

Output:


i = 1
i = 2
i = 3

Break in Nested Loops

In nested loops, the break statement only terminates the loop in which it is written. If a break occurs inside the inner loop, only the inner loop stops, while the outer loop continues to run. This is extremely useful for scenarios such as matrix processing, pattern printing, and multidimensional data structures. Developers must understand this behaviour to avoid logic errors when working with nested loops. The next example demonstrates this clearly.


public class BreakNested {
    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 5; j++) {
                if (j == 3) {
                    break;
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}

Output:


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

Labeled Break Statement

A labeled break allows developers to terminate a specific outer loop instead of only the inner loop. This is extremely beneficial when dealing with complex nested loop structures where breaking only the inner loop is insufficient. A label is a user-defined name followed by a colon, placed before a loop. Using a labeled break, we can exit multiple levels of loops instantly. This improves efficiency and reduces complicated logic.


public class LabeledBreak {
    public static void main(String[] args) {

        outerLoop:
        for (int i = 1; i <= 5; i++) {

            for (int j = 1; j <= 5; j++) {
                if (j == 3) {
                    break outerLoop;
                }
                System.out.println("i=" + i + ", j=" + j);
            }
        }
    }
}

Output:


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

Java Continue Statement

What Is the Continue Statement?

The continue statement in Java is another important jump statement that forces the loop to skip its current iteration and move to the next iteration. Instead of stopping the loop entirely, continue ensures that the loop continues running but bypasses the remaining statements in the current cycle. It is especially useful when you want to avoid certain values, filter data, or skip invalid conditions. Continue improves code readability and efficiency, particularly in conditional filtering, validation checks, and pattern-oriented programs.

Syntax of Continue Statement

Like break, the continue statement uses a simple one-line syntax. It is used inside loops like for, while, and do-while. When encountered, Java immediately jumps to the next iteration of the loop. In a while loop, continue jumps to the condition check, whereas in a for loop, it moves to the update expression. The general syntax is:


continue;

Example 1 – Continue in a For Loop

This example prints numbers from 1 to 10 but skips the value 5 using the continue statement. When i equals 5, continue causes Java to skip printing that number and move to the next iteration. This helps illustrate how continue helps in skipping specific steps during loop execution.


public class ContinueExample1 {
    public static void main(String[] args) {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                continue;
            }
            System.out.println("Value: " + i);
        }
    }
}

Output:


Value: 1
Value: 2
Value: 3
Value: 4
Value: 6
Value: 7
Value: 8
Value: 9
Value: 10

Example 2 – Continue in a While Loop

This example uses continue within a while loop. When the counter reaches 3, the continue statement skips the printing statement and moves back to the condition check. As a result, the number 3 is not printed. This example shows how continue behaves in while loops where the update expression must be placed carefully to avoid infinite loops.


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

        while (i <= 5) {
            if (i == 3) {
                i++;
                continue;
            }
            System.out.println("i = " + i);
            i++;
        }
    }
}

Output:


i = 1
i = 2
i = 4
i = 5

Example 3 – Continue in a Do-While Loop

In a do-while loop, continue forces the program to skip the statements below it and move directly to the condition check. This example shows how continue can be used to skip unwanted values in a do-while loop. When i becomes 2, continue is triggered, and the value 2 is not printed.


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

        do {
            if (i == 2) {
                i++;
                continue;
            }

            System.out.println("i = " + i);
            i++;

        } while (i <= 4);
    }
}

Output:


i = 1
i = 3
i = 4

Labeled Continue Statement in Java

Java allows labeled continue for more complex nested loops. Using a labeled continue, the program skips the current iteration of the labeled loop instead of only the inner loop. This enables developers to control loop iterations in multidimensional structures. This is used in scenarios such as processing 2D arrays, grid patterns, or validating specific rows of data. Below is an example demonstrating a labeled continue.


public class LabeledContinue {
    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

Difference Between Break and Continue Statements

Although both break and continue belong to Java’s jump statements, they behave differently. Break terminates the entire loop, while continue skips only the current iteration. Break passes control outside the loop, but continue transfers control to the next iteration. Break is useful when you want to stop searching or exit prematurely, whereas continue is useful for filtering or validation. Understanding the difference helps developers choose the right statement based on the program's requirement.

Break and continue statements are essential control flow tools in Java that help developers manage loops more effectively. The break statement is used to terminate loops or switch blocks completely, while the continue statement helps skip specific iterations. Both statements make programs cleaner, more readable, and optimized. These statements are frequently used in real-world applications such as searching, filtering, validating data, handling errors, and optimizing algorithms. Mastering break and continue is fundamental for any Java programmer aiming to write efficient and professional-level Java applications.

logo

Java

Beginner 5 Hours

Break and Continue Statements in Java

Java provides several powerful control flow statements that help developers manage how loops and conditional structures behave. Among these, the break statement and the continue statement are two of the most frequently used control flow tools in Java programming. These statements help programmers control loop execution, stop iterations, skip steps, and create more optimized and readable code. This detailed HTML document explains Java break and continue statements with meaning, syntax, real-life use cases, complete Java programs, and outputs. Every concept is explained in 10–15 lines for clarity and SEO-rich understanding.

Introduction to Jump Statements in Java

Jump statements in Java allow the flow of program execution to jump from one point to another. They are essential for controlling loops, decision-making, and enhancing efficiency. Break and continue statements fall under this category. A jump statement helps terminate loops, skip iterations, leave switch blocks, and alter the normal execution of a program. These keywords make Java programs cleaner and more flexible. They reduce the need for complex conditional structures and help developers handle real-time scenarios like searching, filtering, and validating data.

Java Break Statement

What Is the Break Statement in Java?

The break statement in Java is a jump statement used to immediately terminate the execution of a loop or a switch block. When Java encounters a break statement inside a loop, the loop stops running instantly, and control moves to the next statement after the loop. It is widely used in situations where continuing the loop is unnecessary or inefficient. The break statement enhances performance by avoiding unnecessary iterations. It is particularly useful in searching algorithms, menu-driven programs, infinite loops, and nested loops. Understanding break is crucial for writing efficient and optimized Java programs.

Syntax of Break Statement

The syntax of the break statement is very simple and consists of a single keyword. It does not require parentheses, conditions, or expressions. In normal usage, break is included inside a loop or a switch case. When executed, it stops the nearest loop or switch block. The simplicity of its syntax makes it easy to integrate into any Java program. Break can also be used with labels, allowing developers to terminate specific loops within nested loops. The general syntax is shown below:

break;

Example 1 – Basic Break Statement in a For Loop

Below is a simple Java program demonstrating how the break statement works inside a for loop. The loop is designed to print values from 1 to 10, but when the value reaches 5, a break statement is triggered. This stops the loop immediately, and no further iterations are executed. This example helps beginners clearly understand how break interrupts loop execution.

public class BreakExample1 { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { break; } System.out.println("Value: " + i); } } }

Output:

Value: 1 Value: 2 Value: 3 Value: 4

Example 2 – Break Statement in a While Loop

This example shows how break operates inside a while loop. A counter variable is incremented in each iteration. When the counter reaches 7, the break statement executes, stopping the loop immediately. This demonstrates that break works in all Java loops, not just for loops. It also helps understand how break can control infinite loops by manually terminating them at specific conditions.

public class BreakExample2 { public static void main(String[] args) { int i = 1; while (i <= 10) { System.out.println("Number: " + i); if (i == 7) { break; } i++; } } }

Output:

Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Number: 6 Number: 7

Example 3 – Break Statement in Do-While Loop

The break statement works similarly in a do-while loop. The loop runs at least once, and upon reaching a specific condition, the break statement stops the loop. This example prints numbers from 1 to 5, and when the number becomes 3, the break keyword ends the loop. This helps illustrate how break is used across all loop structures in Java.

public class BreakExample3 { public static void main(String[] args) { int i = 1; do { System.out.println("i = " + i); if (i == 3) { break; } i++; } while (i <= 5); } }

Output:

i = 1 i = 2 i = 3

Break in Nested Loops

In nested loops, the break statement only terminates the loop in which it is written. If a break occurs inside the inner loop, only the inner loop stops, while the outer loop continues to run. This is extremely useful for scenarios such as matrix processing, pattern printing, and multidimensional data structures. Developers must understand this behaviour to avoid logic errors when working with nested loops. The next example demonstrates this clearly.

public class BreakNested { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 5; j++) { if (j == 3) { break; } System.out.println("i=" + i + ", j=" + j); } } } }

Output:

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

Labeled Break Statement

A labeled break allows developers to terminate a specific outer loop instead of only the inner loop. This is extremely beneficial when dealing with complex nested loop structures where breaking only the inner loop is insufficient. A label is a user-defined name followed by a colon, placed before a loop. Using a labeled break, we can exit multiple levels of loops instantly. This improves efficiency and reduces complicated logic.

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

Output:

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

Java Continue Statement

What Is the Continue Statement?

The continue statement in Java is another important jump statement that forces the loop to skip its current iteration and move to the next iteration. Instead of stopping the loop entirely, continue ensures that the loop continues running but bypasses the remaining statements in the current cycle. It is especially useful when you want to avoid certain values, filter data, or skip invalid conditions. Continue improves code readability and efficiency, particularly in conditional filtering, validation checks, and pattern-oriented programs.

Syntax of Continue Statement

Like break, the continue statement uses a simple one-line syntax. It is used inside loops like for, while, and do-while. When encountered, Java immediately jumps to the next iteration of the loop. In a while loop, continue jumps to the condition check, whereas in a for loop, it moves to the update expression. The general syntax is:

continue;

Example 1 – Continue in a For Loop

This example prints numbers from 1 to 10 but skips the value 5 using the continue statement. When i equals 5, continue causes Java to skip printing that number and move to the next iteration. This helps illustrate how continue helps in skipping specific steps during loop execution.

public class ContinueExample1 { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { continue; } System.out.println("Value: " + i); } } }

Output:

Value: 1 Value: 2 Value: 3 Value: 4 Value: 6 Value: 7 Value: 8 Value: 9 Value: 10

Example 2 – Continue in a While Loop

This example uses continue within a while loop. When the counter reaches 3, the continue statement skips the printing statement and moves back to the condition check. As a result, the number 3 is not printed. This example shows how continue behaves in while loops where the update expression must be placed carefully to avoid infinite loops.

public class ContinueExample2 { public static void main(String[] args) { int i = 1; while (i <= 5) { if (i == 3) { i++; continue; } System.out.println("i = " + i); i++; } } }

Output:

i = 1 i = 2 i = 4 i = 5

Example 3 – Continue in a Do-While Loop

In a do-while loop, continue forces the program to skip the statements below it and move directly to the condition check. This example shows how continue can be used to skip unwanted values in a do-while loop. When i becomes 2, continue is triggered, and the value 2 is not printed.

public class ContinueExample3 { public static void main(String[] args) { int i = 1; do { if (i == 2) { i++; continue; } System.out.println("i = " + i); i++; } while (i <= 4); } }

Output:

i = 1 i = 3 i = 4

Labeled Continue Statement in Java

Java allows labeled continue for more complex nested loops. Using a labeled continue, the program skips the current iteration of the labeled loop instead of only the inner loop. This enables developers to control loop iterations in multidimensional structures. This is used in scenarios such as processing 2D arrays, grid patterns, or validating specific rows of data. Below is an example demonstrating a labeled continue.

public class LabeledContinue { 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

Difference Between Break and Continue Statements

Although both break and continue belong to Java’s jump statements, they behave differently. Break terminates the entire loop, while continue skips only the current iteration. Break passes control outside the loop, but continue transfers control to the next iteration. Break is useful when you want to stop searching or exit prematurely, whereas continue is useful for filtering or validation. Understanding the difference helps developers choose the right statement based on the program's requirement.

Break and continue statements are essential control flow tools in Java that help developers manage loops more effectively. The break statement is used to terminate loops or switch blocks completely, while the continue statement helps skip specific iterations. Both statements make programs cleaner, more readable, and optimized. These statements are frequently used in real-world applications such as searching, filtering, validating data, handling errors, and optimizing algorithms. Mastering break and continue is fundamental for any Java programmer aiming to write efficient and professional-level Java applications.

Related Tutorials

Frequently Asked Questions for Java

Java is known for its key features such as object-oriented programming, platform independence, robust exception handling, multithreading capabilities, and automatic garbage collection.

The Java Development Kit (JDK) is a software development kit used to develop Java applications. The Java Runtime Environment (JRE) provides libraries and other resources to run Java applications, while the Java Virtual Machine (JVM) executes Java bytecode.

Java is a high-level, object-oriented programming language known for its platform independence. This means that Java programs can run on any device that has a Java Virtual Machine (JVM) installed, making it versatile across different operating systems.

Deadlock is a situation in multithreading where two or more threads are blocked forever, waiting for each other to release resources.

Functional programming in Java involves writing code using functions, immutability, and higher-order functions, often utilizing features introduced in Java 8.

A process is an independent program in execution, while a thread is a lightweight subprocess that shares resources with other threads within the same process.

The Comparable interface defines a natural ordering for objects, while the Comparator interface defines an external ordering.

The List interface allows duplicate elements and maintains the order of insertion, while the Set interface does not allow duplicates and does not guarantee any specific order.

String is immutable, meaning its value cannot be changed after creation. StringBuffer and StringBuilder are mutable, allowing modifications to their contents. The main difference between them is that StringBuffer is synchronized, making it thread-safe, while StringBuilder is not.

Checked exceptions are exceptions that must be either caught or declared in the method signature, while unchecked exceptions do not require explicit handling.

ArrayList is backed by a dynamic array, providing fast random access but slower insertions and deletions. LinkedList is backed by a doubly-linked list, offering faster insertions and deletions but slower random access.

Autoboxing is the automatic conversion between primitive types and their corresponding wrapper classes. For example, converting an int to Integer.

The 'synchronized' keyword in Java is used to control access to a method or block of code by multiple threads, ensuring that only one thread can execute it at a time.

Multithreading in Java allows concurrent execution of two or more threads, enabling efficient CPU utilization and improved application performance.

A HashMap is a collection class that implements the Map interface, storing key-value pairs. It allows null values and keys and provides constant-time performance for basic operations.

Java achieves platform independence by compiling source code into bytecode, which is executed by the JVM. This allows Java programs to run on any platform that has a compatible JVM.

The Serializable interface provides a default mechanism for serialization, while the Externalizable interface allows for custom serialization behavior.

The 'volatile' keyword in Java indicates that a variable's value will be modified by multiple threads, ensuring that the most up-to-date value is always visible.

Serialization is the process of converting an object into a byte stream, enabling it to be saved to a file or transmitted over a network.

The finalize() method is called by the garbage collector before an object is destroyed, allowing for cleanup operations.

The 'final' keyword in Java is used to define constants, prevent method overriding, and prevent inheritance of classes, ensuring that certain elements remain unchanged.

Garbage collection is the process by which the JVM automatically deletes objects that are no longer reachable, freeing up memory resources.

'throw' is used to explicitly throw an exception, while 'throws' is used in method declarations to specify that a method can throw one or more exceptions.

The 'super' keyword in Java refers to the immediate parent class and is used to access parent class methods, constructors, and variables.

The JVM is responsible for loading, verifying, and executing Java bytecode. It provides an abstraction between the compiled Java program and the underlying hardware, enabling platform independence.

line

Copyrights © 2024 letsupdateskills All rights reserved