What is the usage of the “break” statement in Java?

In Java, the break statement is used to immediately terminate the current loop or switch statement and exit the execution of the loop or switch statement.

In a loop, the break statement is often used in conjunction with an if statement to exit the loop when a specific condition is met. When the break statement is executed, the program will immediately exit the current loop without running the remaining code in the loop, and continue executing the code after the loop.

Here is an example demonstrating how to use the break statement within a for loop with an if statement.

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

The above code will produce:

0
1
2
3
4

When i is equal to 5, the break statement is executed, immediately terminating the loop and therefore the code after number 5 will not be executed.

In a switch statement, the break statement is used to end the current case block and exit the switch statement. If the break statement is not used, the program will continue to execute the code in the next case block. Using the break statement helps avoid unnecessary execution.

Here is an example of a switch statement using the break statement:

int day = 3;
String dayType;

switch (day) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
        dayType = "工作日";
        break;
    case 6:
    case 7:
        dayType = "周末";
        break;
    default:
        dayType = "无效的日期";
        break;
}

System.out.println("今天是" + dayType);

The above code will output:

今天是工作日

The switch statement matches the value of day with the corresponding case. When day is between 1 and 5, dayType is assigned as “Weekday” and the break statement terminates the execution of the switch statement. Without using a break statement, the program will continue to execute the code in the next case block until it encounters a break statement or the switch statement ends.

bannerAds