In The Previous article, we have discussed static access modifiers, and in this article, we are going to learn about the break statement to terminate the loop.
The Java Break keyword mainly used to terminate the loop, that loop may be for, while, do-while or we can use in the switch case-control flow statements. This break keyword also called a break statement.
The Syntax of break statement looks like below
Here we take a for a loop as an example for the use of the break statement, but we can also use it in other loops as well as in switch-case statements.
for(...) { //loop statements break; }
Types of Break Statement
As we mentioned above that a break statement is used to come out from the loop or block. There are two forms of break are there, that is:
- Unlabeled Break statement
- Labelled Break statement
Let’s see examples to understand the difference between unlabeled Vs Labeled break statements easily.
Unlabeled Break Statement
Those break statements used without any labels that are called unlabeled break statements. Those are written as a simple “break;”. An Example of unlabeled break statement is:
int i = 1; while (true) { // Cannot exit the loop from here if (i <= 10) { System.out.println(i); i++; } else { break; // Exit the loop } }
We Can use same in a switch statement also like below
switch (switch-expression) { case label1: statements; break; case label2: statements; break; default: statements; }
Labelled Break Statement
If we Mention a label1 name after the break statement, then that’s called a labelled break statement. You can refer below program, for the labelled break statement:
blockLabel: { int i = 10; if (i == 5) { break blockLabel; // Exits the block } if (i == 10) { System.out.println("i is not five"); } }
Note: The Break Statement terminate the flow of the execution at the labelled break statement, but it doesn’t transfer the flow of execution to that mentioned block name.
One crucial point you have to remember that when you are using the labelled break statement that is ” The Label name used with the break statement should be the same block name where the labelled break statement present otherwise you will get an undefined label error message.”
lab1: { int i = 10; if (i == 10) break lab1; // Ok. lab1 can be used here } lab2: { int i = 10; if (i == 10) // A compile-time error. lab1 cannot be used here because this block is not // associated with the lab1 label. We can use the only lab2 in this block break lab1; }
Ref: article
Leave a Reply