![]() |
VOOZH | about |
The break statement in Java is a control flow statement used to immediately terminate a loop, switch statement, or labeled block. When a break statement is encountered, the program exits the current block and transfers control to the next statement following that block.
GFG
Explanation: In the above example, the switch statement is evaluated with n = 1. The case 1 block matches and prints "GFG". The break statement then exits the switch block, preventing the execution of any remaining cases.
break;
The break statements are used in situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition.
When the Java compiler encounters a break statement, it immediately exits the current loop, switch block, or labeled block and continues execution with the next statement outside that block.
In a switch statement, the break statement prevents execution from continuing into subsequent cases after a match is found.
break exits the switch block.The break statement can terminate a loop as soon as a specified condition becomes true, regardless of the loop condition.
Note: Break, when used inside a set of nested loops, will only break out of the innermost loop.
👁 Using break to exit a loop in java
Example: Java program to illustrate using break to exit a loop
i: 0 i: 1 i: 2 i: 3 i: 4 Loop complete.
Java allows labels to be associated with blocks of code. A labeled break can be used to exit a specific block directly.
Working
Syntax:
label_name: {
// Block of statements
break label_name;
}
Example: Java program to illustrate break statement in labeled blocks
Before break statement After second block.
Explanation: The program enters the first labeled block. It moves into the second labeled block and then into the third labeled block. When t is true, the break second; exits the second block by skipping all further code within it. The program then prints "After second block."