0% completed
The break statement in Java is used to immediately terminate the current loop or switch statement. It helps in controlling the flow of the program by exiting from a loop or switch when a specific condition is met. The break statement can be very useful in preventing unnecessary iterations or in exiting nested loops.
break;
break;
terminates the loop or switch.Below is an example that uses a for loop to iterate through numbers and breaks out of the loop when the number 3 is reached.
Explanation:
i
equals 3, the break statement is executed, terminating the loop immediately.Below is an example that uses the break statement in a switch case to prevent fall-through.
Explanation:
day
.day
equals 4, the corresponding case prints "Thursday".By using the break statement, you can control the flow of your loops and switch statements more effectively. It ensures that once a desired condition is met, no unnecessary processing takes place. Experiment with these examples and try modifying the conditions to see how break affects program execution.
.....
.....
.....