Java break Statement

www.ig‮aeditfi‬.com

In Java, the break statement is used to immediately terminate a loop or switch statement and continue executing the next statement after the loop or switch block. When a break statement is encountered in a loop or switch statement, the control is transferred to the statement immediately following the loop or switch block.

Here's the basic syntax of the break statement in Java:

break;

The break statement can be used in loops such as for, while, and do-while loops, as well as in switch statements.

In a for loop, the break statement is often used to exit the loop early if a certain condition is met. For example, the following code uses a for loop to iterate over an array of integers and breaks out of the loop when it finds a number that is greater than 10:

int[] numbers = { 2, 4, 6, 8, 10, 12, 14 };
for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] > 10) {
        break;
    }
    System.out.println(numbers[i]);
}

In this code, the loop iterates over the array of integers and prints out each number that is less than or equal to 10. When the loop encounters the number 12, which is greater than 10, it executes the break statement, which immediately terminates the loop and continues with the statement after the loop.

In a switch statement, the break statement is used to prevent fall-through, which occurs when the program execution falls through from one case to the next case without stopping. Here's an example of a switch statement that uses the break statement to prevent fall-through:

int dayOfWeek = 2;
switch (dayOfWeek) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Unknown day of the week");
        break;
}

In this code, the switch statement checks the value of the dayOfWeek variable and executes the code block for the matching case. Each case block includes a break statement, which terminates the switch statement and continues with the statement after the switch block. If there is no matching case, the default block is executed, which also includes a break statement.