Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Break Any Outer Nested Loop by Referencing its Name in Java

  • Last Updated : 21 Oct, 2020

A nested loop is a loop within a loop, an inner loop within the body of an outer one.

Working:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

  1. The first pass of the outer loop triggers the inner loop, which executes to completion. 
  2. Then the second pass of the outer loop triggers the inner loop again. 
  3. This repeats until the outer loop finishes. 
  4. A break within either the inner or outer loop would interrupt this process.

The Function of Nested loop :

Java




// Nested for loop
  
import java.io.*;
class GFG {
  
    public static void main(String[] args)
    {
  
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print("GFG! ");
            }
            System.out.println();
        }
    }
}
Output



GFG! GFG! GFG! 
GFG! GFG! GFG! 
GFG! GFG! GFG! 

Label the loops:

This is how we can label the name to the loop:

labelname :for(initialization;condition;incr/decr){  
    //code to be executed  
}  

Java




// Naming the loop
  
import java.io.*;
  
class GFG {
  
    public static void main(String[] args)
    {
  
    // Type the name outside the loop
    outer:
        for (int i = 0; i < 5; i++) {
            System.out.println("GFG!");
        }
    }
}
Output
GFG!
GFG!
GFG!
GFG!
GFG!

Rules to Label the loops:

  1. Label of the loop must be unique to avoid confusion.
  2. In the break statements use labels that are in scope. (Below is an implementation)

Java




// Break statements and naming the loops
  
import java.lang.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
    // Using Label for outer and for loop
    outer:
        for (int i = 1; i <= 3; i++) {
        // Using Label for inner and for loop
        inner:
            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    break inner;
                }
                System.out.println(i + " " + j);
            }
            if (i == 2) {
                break outer;
            }
        }
    }
}
Output
1 1
2 1



My Personal Notes arrow_drop_up
Recommended Articles
Page :