
Java Break
The break statement in Java is used to exit from a loop or a switch statement prematurely. It allows you to immediately terminate the execution of the innermost loop or exit from a switch statement. The break statement is commonly used to control the flow of your program in various situations.
Here’s how the break statement is used in different contexts:
- Breaking from a Loop:
Thebreakstatement is often used in loops, such asfor,while, anddo-while, to exit the loop before it completes all its iterations.
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println(i);
}
In this example, the loop will exit when i becomes 5, and the remaining iterations will be skipped.
- Breaking from a Switch:
Thebreakstatement is used in aswitchstatement to exit the switch block after executing a case. Withoutbreak, execution would “fall through” to the next case.
int day = 2;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
default:
System.out.println("Other day");
}
In this example, when day is 2, “Monday” will be printed, and the break statement will exit the switch statement. Without the break, both “Monday” and “Other day” would be printed.
- Breaking from Labeled Blocks:
You can also use thebreakstatement to exit from a labeled block or nested loops. A labeled block is marked with an identifier followed by a colon, and you can specify the label as an argument tobreak.
outerLoop: for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i * j == 12) {
break outerLoop; // Exit both loops when i*j is 12
}
System.out.println(i * j);
}
}
In this example, when i * j equals 12, the break statement with the label outerLoop will exit both the outer and inner loops.
The break statement provides a way to control the flow of your program and is useful for exiting loops or switch statements when certain conditions are met. It is important to use it judiciously to avoid unexpected program behavior.