In Java, the break keyword serves as a command to halt the execution of a for loop, while loop, or switch-case construct. Once encountered, the program flow moves to the next statement outside the construct.
Consider the following example where a break statement is used within a for loop:
// Using break in a for loop to find the first even number
for (int i = 1; i <= 10; i++) {
System.out.println("Checking: " + i);
if (i % 2 == 0) {
System.out.println("Found the first even number: " + i);
break;
}
}
In this scenario, the for loop prints the values of count
from 0 to 70. When count
exceeds 70, the break statement intervenes, terminating the loop.
Now, observe the use of the break statement in a while loop:
// Using break in a while loop to exit when a condition is met
int countdown = 5;
while (countdown > 0) {
System.out.println("Countdown: " + countdown);
if (countdown == 3) {
System.out.println("Abort mission! Countdown interrupted.");
break;
}
countdown--;
}
In this scenario, the while loop counts down from 5 to 1. The program prints each countdown value but interrupts the countdown when it reaches 3, using the break statement.
In the case of a switch statement, the break statement is employed within each case to prevent execution from cascading into subsequent cases:
// Using break in a switch statement to find the day of the week
int dayNumber = 4;
String dayName = "";
switch(dayNumber) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Other day";
break;
}
System.out.println("Today is " + dayName);
In this straightforward switch statement, the program identifies the day of the week based on dayNumber
. If the day is not explicitly handled, it falls into the "Other day" case, and the break statement ensures the correct day name is printed
In essence, the break keyword acts as a control mechanism, allowing developers to manage the flow of their programs within loops and switch statements.