In Java, the break keyword is used to terminate the execution of a loop or a switch statement.
When used inside a loop, the break keyword causes the loop to exit immediately and resume execution at the next statement after the loop. This is useful when you want to terminate a loop early based on some condition.
Here's an example of using break inside a for loop:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
In this example, the loop will iterate 10 times, printing the values of i from 0 to 4. When i is equal to 5, the break statement is executed, causing the loop to exit immediately, and the program will continue executing the next statement after the loop.
The break keyword can also be used inside a switch statement. In this case, the break keyword is used to exit the switch statement and resume execution at the next statement after the switch.
Here's an example of using break inside a switch statement:
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown day";
break;
}
System.out.println(dayName);
In this example, the switch statement checks the value of the day variable and assigns the corresponding day name to the dayName variable. When day is equal to 3, the case 3 block is executed, and the break statement causes the switch statement to exit immediately. The program then continues executing the System.out.println(dayName) statement, which prints the value of dayName, which in this case is "Wednesday".