Junior — Middle
What does the break operator do and in what cases is it used in programming?
sobes.tech AI
Answer from AI
The break operator in Java is used to immediately exit a loop (for, while, do-while) or a switch block. When execution reaches break, the current loop or switch is terminated, and control passes to the next statement after the loop or switch.
Often, break is used to:
- Exit a loop upon reaching a certain condition, for example, when a desired element is found.
- In a
switchstatement — to prevent execution of subsequent cases (to avoid "fall-through").
Example of usage in a loop:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit the loop when i equals 5
}
System.out.println(i);
}
// Will print numbers from 0 to 4
Example in a switch:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Other day");
break;
}