Java break Statement

In this tutorial, we will learn how to use the Java break statement to terminate a loop or switch statement.

While working with loops, it is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression.

In such cases, break and continue statements are used.

The break statement in Java terminates the loop immediately, and the control of the program moves to the next statement following the loop.


1. Java break statement

The syntax of the break statement in Java is:

break;

Example 1: Java break statement

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

        // for loop
        for (int i = 1; i <= 10; ++i) {

            // if the value of i is 5 the loop terminates
            if (i == 5) {
                break;
            }
            System.out.println(i);
        }
    }
}

Output:

1
2
3
4

2. Labeled break Statement

In Java, we can use the break statement to terminate a specific loop in nested loops. This is done by using a label.

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

        // the for loop is labeled as first
        first:
        for( int i = 1; i < 5; i++) {

            // the for loop is labeled as second
            second:
            for(int j = 1; j < 3; j ++ ) {
                System.out.println("i = " + i + "; j = " +j);

                // the break statement breaks the first for loop
                if ( i == 2)
                    break first;
            }
        }
    }
}

Output:

i = 1; j = 1
i = 1; j = 2
i = 2; j = 1

Here, when i is 2, break first; is executed, which terminates the outer loop labeled first.


Key Takeaways

  • Action: Terminates the loop immediately.
  • Flow: Control jumps to the code after the loop.
  • Labeled Break: Used to exit nested loops from the inner loop.

Common Pitfalls

[!WARNING] Unreachable Code: Any code written immediately after break; in the same block will cause a compile-time error because it can never be reached.

Challenge

Challenge

Task:

Use break to stop the loop when i is 4. Loop runs from 1 to 5.