In this tutorial we will discuss about break statement in java 7.

Break Statement in java 7
In this tutorial we will discuss about break statement in java 7.
Break Statement :
Java facilitate you to break the flow of your program by using break statement. The break statement breaks the flow of your loop (do-while, while, for or switch statement). In switch statement we use break at the end of each case.
There is two kinds of break statement -
- labeled
- unlabeled
1. Unlabeled Statement :
Unlabeled break statement terminate the loop like while, do-while, for and switch. When you call break it jumps out of the recent specified loop. It breaks the innermost for, while, do-while, switch statement.
Example :
This is a simple example of unlabeled break statement.
package branching;
class UnlabeledBreakStatement {
public static void main(String[] args) {
int i;
for (i = 1; i <= 5; i++) {
System.out.println("Hello i is less than 3.");
if (i == 3) {
System.out.println("Value of i is 3.Now break..");
System.out.println("It is unlabeled break statement..");
break; // using break statement to break for loop.
}
}
}
Output :
Hello i is less than 3. Hello i is less than 3. Hello i is less than 3. Value of i is 3.Now break.. It is unlabeled break statement..
Labeled Statement :
If you want to terminate the outer statement java provides the way to do this by using labeled break statement. You can jump out from the multiple or nested loop.
Example :
package branching;
class LabeledBreakStatement {
public static void main(String[] args) {
int matrix[][] = { { 4, 5, 6 }, { 12, 5, 20 } };
labeledBreak: for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] > 10) {
System.out.println("Labeled break statement is called...");
break labeledBreak;
}
System.out.println("Value of matrix is less than 10 : "
+ matrix[i][j]);
}
}
}
}
Output :
Value of matrix is less than 10 : 4 Value of matrix is less than 10 : 5 Value of matrix is less than 10 : 6 Labeled break statement is called...