Java break Statement [with Examples]

Java Tutorials

Summary: In this tutorial, you will learn about break statement in Java. You will learn how break statement stops the execution of loops with the help of examples.

Break Statement in Java

The break statement is used to exit a loop early or to skip a case in a switch statement.

When the break statement is encountered inside a loop, it will immediately exit the loop and continue executing the code after the loop.

Here is an example of using the break statement to exit a loop:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}

In this example, the loop will iterate from 0 to 4 and print the numbers to the console. When the loop variable i becomes 5, the break statement is encountered and the loop is immediately exited.

The break statement can also be used in a switch statement to skip a case. Here is an example:

int x = 1;
switch (x) {
    case 1:
        System.out.println("x is 1");
        break;
    case 2:
        System.out.println("x is 2");
        break;
    default:
        System.out.println("x is not 1 or 2");
        break;
}

In this example, the output would be “x is 1” because the break statement is encountered after the first case is executed.

If the break statement were not present, the code for the remaining cases would also be executed.

Example: Exiting a nested loop

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        if (j == 5) {
            break;
        }
        System.out.println(i + " " + j);
    }
}

In this example, the inner loop will iterate from 0 to 4 and print the values of i and j to the console.

When the loop variable j becomes 5, the break statement is encountered and the inner loop is immediately exited.

The outer loop will continue iterating and the inner loop will start over again with a new value of i. This will continue until the outer loop has completed all of its iterations.


Leave a Reply

Your email address will not be published. Required fields are marked *