In Java, we can label the loops and give them names. These named or labeled loops help in the case of nested loops when we want to break or continue a specific loop out of those multiple nested loops.
The labeled blocks in Java are logically similar to goto
statements in C/C++.
1. Syntax
A label is any valid identifier followed by a colon. For example, in the following code, we are creating two labeled statements:
outer_loop:
for (int i = 0; i < array.length; i++) {
inner_loop:
for (int j = 0; j < array.length; j++) {
//...
}
//...
}
In the above example, we have two loops, and we have labeled them as outer_loop and inner_loop. This is helpful when we want to terminate the outer loop from a condition written in the inner loop.
2. Difference between Simple break and Labeled break
The simple break statement in Java terminates only the immediate loop in which it is specified. So even if we break from the inner loop, it will still continue to execute the current iteration of the outer loop.
We must use the labeled break statement to terminate a specific loop, as the outer_loop in the above example.
In the same way, we can use the labeled continue statements to jump to the next iteration of any specific loop in the hierarchy of nested loops.
continue outer_loop;
3. Labeled Statement with Other Conditional Statements
It is worth mentioning that labeled break and continue statements can be used with other flow control statements such as if-else statements, while-loop etc.
The following program uses the labeled break statement with a while-loop. Whenever during the program execution, the labeled break statement is encountered, then the control immediately goes out of the enclosing labeled block.
hackit:
while (Some condition)
{
if ( a specific condition )
break hackit; //label
else
//normal business logic goes here..
}
Similarly, we can use these statements with the classical if-else statements as well.
int i = 10;
outer_if:
if(i > 0) {
inner_if:
if( i> 5) {
//...
break outer_if;
} else {
//...
}
}
4. Conclusion
In this simple Java tutorial, we discussed the following points:
- Java does not have a general
goto
statement like a few other programming languages. - The simple
break
andcontinue
alter the normal flow control of the program. We can specify the named labels. A label should be a valid java identifier with a colon. - Labeled blocks can only be used with
break
andcontinue
statements. - Labeled break and continue statements must be called within their scope. We can not refer them outside the scope of the labeled block.
- The
break
statement immediately jumps to the end (and out) of the appropriate compound statement. - The
continue
statement immediately jumps to the appropriate loop’s next iteration (if any).
Happy Learning !!
Leave a Reply