Java break
Created By: chatGPT
The
break
statement in Java is used to terminate a loop or a switch statement. When the break
statement is executed, control is transferred to the statement that follows the loop or switch. This allows for flexible control flow within loops and switch cases.for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
System.out.println(i);
}
// Output: 0, 1, 2, 3, 4
In nested loops, a
break
statement will only terminate the nearest loop. If you want to exit from an outer loop, you can use a labeled break. Labeled break
allows you to specify which loop to terminate.outerLoop:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (j == 2) {
break outerLoop; // Exits both loops when j equals 2
}
System.out.println(i + " " + j);
}
}
// Output: 0 0, 0 1, 1 0, 1 1
Best practices suggest using
break
statements carefully to avoid complicated control flows that might make code harder to read. Code clarity should always be prioritized. By adhering to this guideline, you improve both maintainability and readability of your code.while (true) {
System.out.println("Looping...");
if (someCondition) {
break; // Exits the infinite loop when someCondition is true
}
}