In several instances, such as an error or incorrect input from the user, it may be necessary for the flow of control to exit from a loop statement. To accomplish this, Java provides a jump statement called break statement.
The break statement forces the control to come out from a switch statement, a while loop, a do-while loop or a for loop. After the control moves out of a switch statement or any loop statement, it moves to the statement after the loop or switch statement.
The break statement is written as break; without any expression.
Consider a program that prints the value stored in a variable until the specified condition is false. The program ends when the value becomes equal to the value stored in another variable.
The break statement has been used to enable the program to end when the value in the i variable becoes equal to the value in the num variable. If the value in the i variable is less than 10, the flow of control enters the for loop. When the code is executed, the program displays the numbers from 0 to 3.
Labelled Brake statement
In a nested loop, the break statement used in an inner loop transfers the flow of control to the immediate outer loop. In certain situations, you may also want the flow of control to exit the outer loop. In this case, you use the break statement with the label identifier.
The label identifier is used to group a loop statement that contains another loop statement or a switch statement and to specify the name for the group. The label identifier is specified just before a loop statement without any expression like ‘label_name: ‘.
For example, to name the loop statement label1, you write label1: in the line preceding the loop statement.
When the brake statement is used with the label_name, the flow of control is transferred to the statement after the labeled loop.
Consider the code displayed above. that displays the value stored in variable ‘i’ until the condition specified in either of the for loops becomes false. The program terminates if the value of ‘i’ becomes equal to that of ‘num’. In the code shown above, a label statement, ‘label1:’ has been used to group the two for loops.
When the value of the ‘i’ variable becomes equal to the value of the ‘num’ variable, the program executes the labeled brake statement. This transfers the flow of control outside label1. Therefore, the print statement outside the nested for statement is not executed.
HINT: You cannot use the break statement without a switch statement or a loop statement.