How Do I Break Out Of Nested Loops In Java?

In this Tutorial, we learn How To I Break Out Of Nested Loops In Java? as we can come out of a loop in two ways one by using break statements to come out of the function and the other could be returning the value which also breaks out of all the loops.

Break Out Of Nested Loops In Java

Nested Loops

Nested loops are the loops inside a loop where a loop in there inside a loop. The complexity of such programs become expositional as many loops that the number of power on complexity.

Here we will discuss the ways to come out of the loops using different keywords.

Break Statement To Come Out Of Loop

The break is a statement that is used to come out of the current loop where currently executing the program is whatever the condition is as soon as this statement is executed the control is come out of the executing loop.

We can also have leveled break statements where we can specify the break till where we want to come out of loops.

Let’s understand with some examples.

class LabeledBreak {
    public static void main(String[] args) {
   
        // the for loop is labeled as first   
        first:
        for( int i = 1; i < 5; i++) {

            // the for loop is labeled as second
            second:
            for(int j = 1; j < 3; j ++ ) {
                System.out.println("i = " + i + "; j = " +j);
             
                // the break statement breaks the first for loop
                if ( i == 2)
                    break first;
            }
        }
    }
}

Here we can see how we have described the break statement till what statement we can come out of the loop.

Use Of Return Statement To Come Out Of Loops

Return is a statement that is used not only to come out of all the loops but also to pass the control out of the function and return the value to the caller of the function.

Sometimes it might prove wrong to use as it closes all the loops and return the value to the call that was at that time which might not be calculated fully.

Learn More about How Do I Break Out Of Nested Loops In Java? at: Nested loop

And also visit Java Tutorialsto solve more problems of java and also visit Python’s list: What is the difference Between methods Append and Extend? For python related problems.

 

 

Leave a Comment

%d bloggers like this: