Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud

Write a Java program to demonstrate the usage of break and continue statements inside a While loop?

In Java, break and continue are jump statements used inside a while loop to control its flow. break immediately terminates the loop and moves control to the statement after it, while continue skips the rest of the current iteration and jumps back to re-evaluate the loop condition. Both work in for, while, and do-while loops.

The two statements let you ignore specific statements within a loop or abruptly exit it without waiting for the test expression to become false. Below are runnable examples that show exactly how each behaves.

Understanding the break Statement in a While Loop

The break statement immediately terminates the loop it sits in and transfers control to the first statement after the loop. In a while loop it is often used to exit an otherwise infinite loop once an exit condition is met. Once break executes, the loop will not run again.

Following is the Java program that demonstrates the use of the break statement inside a while loop.

Code:


public class Example {
public static void main(String[] args) {
    //initiating while loop
    int a = 1;
    while(a <= 10){
        if(a == 5){
            //using break statement
            a++;
            break; //it will break the while loop
        }
        System.out.println(a);
        a++;
    }
}
}

Output:

1

2

3

4

The loop prints 1 to 4. When a becomes 5, the if block runs break and the loop ends before 5 is printed, so nothing from 5 onward appears.

Understanding the continue Statement in a While Loop

The continue statement breaks only the current iteration when a specified condition occurs and continues with the next iteration. The lines after continue are skipped for that iteration only, then the loop condition is checked again. Be careful in a while loop: if continue appears before the increment or decrement step, the counter never updates and you can end up in an infinite loop.

Following is the Java program that demonstrates the use of the continue statement inside a while loop.

Code:


public class Example {
public static void main(String[] args) {
    //initiating while loop
    int a = 1;
    while(a <= 10){
        if(a == 5){
            //using continue statement
            a++;
            continue; //it will skip the remaining statement
        }
        System.out.println(a);
        a++;
    }
}
}

Output:

1

2

3

4

6

7

8

9

10

Here 5 is skipped because continue jumps past the print statement for that iteration, but the loop keeps running and prints the remaining values up to 10.

break vs continue: Key Differences

  • Effect on the loop: break exits the loop at once; continue only ends the current iteration.
  • What runs next: after break, control goes to the code after the loop; after continue, the loop condition is re-checked.
  • Remaining iterations: break cancels all remaining iterations; continue preserves them.
  • Common use: break for an early exit when a target or error is found; continue to skip unwanted values.

Labeled break in Nested Loops

An unlabeled break only terminates the loop it is currently in. If that loop is nested inside another loop, the outer loop is not stopped. To exit an outer loop from inside a nested loop, use a labeled break by placing a label before the outer loop.

public class LabeledBreak {
public static void main(String[] args) {
    int i = 1;
    outer:
    while(i <= 3){
        int j = 1;
        while(j <= 3){
            if(i == 2 && j == 2){
                //exits BOTH loops
                break outer;
            }
            System.out.println("i=" + i + ", j=" + j);
            j++;
        }
        i++;
    }
}
}

Without the label, break would only leave the inner while loop and the outer loop would continue. The label lets a single statement stop both loops cleanly.

Common Mistakes and Troubleshooting

  • continue before the increment: placing continue ahead of a++ skips the counter update and creates an infinite loop. Always update the counter first.
  • Expecting break to exit all loops: an unlabeled break leaves only the innermost loop. Use a labeled break for outer loops.
  • Unreachable code after break or continue: statements written directly after them in the same block never execute and cause a compile error.
  • Confusing skip with exit: using break when you meant continue silently drops the rest of the data. Match the statement to the intent.
  • Missing braces: without braces on the if, only the next single line is guarded, which changes which statement break or continue applies to.

Conclusion

The break statement exits a while loop entirely, while continue skips the current iteration and moves on. Remember to update your loop counter before continue to avoid infinite loops, and reach for a labeled break when you need to exit nested loops. Used deliberately, these jump statements make loop logic in Java both cleaner and more predictable.

Frequently Asked Questions

What is the difference between break and continue in a Java while loop?

break exits the loop entirely and control moves to the statement after the loop, so no further iterations run. continue only skips the rest of the current iteration and jumps back to re-evaluate the loop condition, so the loop keeps running.

Why does continue cause an infinite loop in a while loop?

In a while loop the counter is updated inside the body. If continue appears before the increment or decrement step, that update is skipped, so the condition never changes and the loop runs forever. Always update the counter before continue.

Can break and continue be used in the same while loop?

Yes. You can use both in one loop to control different conditions. For example, continue can skip even numbers while break stops the loop once a target value is reached. Each statement is triggered by its own if condition.

Does break exit all nested loops in Java?

No. An unlabeled break exits only the innermost loop that contains it; the outer loop keeps running. To break out of an outer loop from inside a nested loop, use a labeled break with a label placed before the outer loop.

Do break and continue work in do-while and for loops too?

Yes. break and continue are jump statements that work in all Java loops, including for, while, and do-while. break terminates the loop and continue skips to the next iteration, following the same rules in each loop type.

Is it good practice to use break and continue?

Used sparingly, they make loops clearer by handling exit and skip conditions early. Overusing them, or nesting many of them, can make control flow hard to follow. Keep conditions simple and prefer a single, well-named exit point where possible.

Related Questions

Test Your Website on 3000+ Browsers

Get 100 minutes of automation test minutes FREE!!

Test Now...

KaneAI - Testing Assistant

World’s first AI-Native E2E testing agent.

...

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests