JAVA

[ Solved -1 Answers] JAVA – Breaking out of nested loops in Java

Breaking out of nested loops in Java Label in Java is little different then goto. labeled break has no similarity

Java Code
A nested loop,
for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

How break out of both loops occurs

  • There are situations we need to be nested loops in Java, one loop containing another loop e.g. to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in a two-dimensional array.
  • Nesting looping e.g. printing pascal triangle and printing those star structures exercises from school days.
    Depending upon some condition we also like to come out of both inner and outer loop.

For example, while searching a number in a two-dimensional array, once you find the number, you want to come out of both loops. There is a feature called labeled break, which you can use to break from nested loop. Label with break you can terminate a particular loop in nested loop structure.

How to use Label in Java

  • There are two steps to break from nested loop, first part is labeling loop and second part is using labeled break.
  • We must put our label before loop and need a colon after the label.
  • When using that label after break, control will jump outside of the labeled loop. This means if there are 10 level of nested loop, it can break from all of them by just calling break and label of first loop. Similarly using labeled continue, it starts continuing from the labeled loop
  • Label in Java is little different then goto. labeled break has no similarity with goto because it don’t allow you to go on a particular line, all you go is outside the loop.
  • Labeled continue is little bit similar to goto because it goes to the loop again but not at any arbitrary point, since continue can only be used with loop, effect is limited to the loops only.
  • To exit at any point inside an inner loop better use return statement. For this we need to externalize the code into a method and then call it, now at any point if want to go out of the loop, just call return without any value. This will improve readability.

How to break from nested Loop in Java

  • The sample code of breaking nested loop in Java, we just have two loops, OUTER and INNER.
  • We are printing number in both the loop but once the product of two counters exceed 5, we break out from the outer loop.
  • This makes program complete because we also come out of main method.
  • In the next example, the same logic has been developed using a method and return statement called breakFromNestedLoop()
  • To break out from nested loop consider using a method and return statement over labeled break statement.
Java Code
import java.io.IOException;
 /** * How to break from nested loop in Java. You can use labeled * statement with break statement to break from nested loop.  */ 
public class BreakingFromNestedLoop{ public static void main(String args[]) throws IOException
 { 
// this is our outer loop 
outer: for (int i = 0; i < 4; i++) 
{ 
// this is the inner loop 
for (int j = 0; j < 4; j++) 
{ 
// condition to break from nested loop
 if (i * j > 5)
 { 
System.out.println("Breaking from nested loop"); 
break outer;
 } 
System.out.println(i + " " + j); 
} } 
System.out.println("exited");
Java Code
// better way is to encapsulate nested loop in a method 
// and use return to break from outer loop 
breakFromNestedLoop(); 
} 
/** * You can use return statement to return at any point from a method. 
* This will help you to break from nested loop as well */ 
public static void breakFromNestedLoop()
{ 
for(int i=0; i<6; i++)
{ 
for(int j=0; j<3; j++)
{ 
int product = i*j; 
if(product > 4)
{ 
System.out.println("breaking from nested loop using return"); return; 
} } }
System.out.println("Done"); } }

Output

0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
Breaking from nested loop
exited
breaking from nested loop using return

READ  Java Algorithm - Search an element in a Linked List both Iterative and Recursive

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X