Thursday, February 13, 2014

How to terminate outer loop from the inner loop in Java ?

1:12 AM

Most of you must be wondering how to terminate the outer loop in java,

as using the break, continue keywords will always terminate the inner loop execution.

consider the following example:

Output:

1 1

1 2

2 1

2 2

in this example the break used inside inner loop will always terminate the inner for loop but not the outer loop.

To terminate the outer loop from the inner loop, java supports label concepts.

How to use label?

if you want to terminate the outer loop from the inner loop,

Just use a label before loop.

Label can be any valid user defined name, there is no restriction in label naming.

Note:

1. Label name must be followed by colon ':'

2. If you don't use colon after label name the program will generate compile time error saying not a statement.

To terminate the loop just use label name just after break/continue keywords.

label name used after the break/continue keyword, will terminate the loop associated with that label name.

Here is the updated code with the use of labels,

Here the name java is a label name for outer loop and ocjp is the label name for inner loop, when the code at line #10 in executed , it terminates the outer loop, as java is the label name for outer loop.