Saturday 10 September 2022

How to break out of nested loops in Java?

In this post, I am going to explain how to break the outer loop in Java.

 

Approach 1: Using labelled break statement.

 

labelled break

label is a group of statements, identified by using labelname.

 

Syntax

labelName: {
      statement 1
      statement 2
      …....
      statement N
    }

 

Syntax to break the label

break labelName;

 

BreakOuterLoopDemo1.java

package com.sample.app.loops;

public class BreakOuterLoopDemo1 {

	public static void main(String[] args) {
		outerLoop: 
			for (int i = 1; i < 10; i++) {
				for (int j = 1; j < 10; j++) {
					if (i * j > 5) {
						System.out.println("Breaking outer loop");
						break outerLoop;
					} else {
						System.out.println("(" + i + "," + j + ")");
					}
				}
				System.out.println("Inner loop executed....");
			}
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop

 

Approach 2: Keep the looping logic in a different method, and return from the method, when you meet the criteria.

 

BreakOuterLoopDemo2.java

package com.sample.app.loops;

public class BreakOuterLoopDemo2 {

	public static void doSomeLogic() {
		for (int i = 1; i < 10; i++) {
			for (int j = 1; j < 10; j++) {
				if (i * j > 5) {
					System.out.println("Breaking outer loop");
					return;
				} else {
					System.out.println("(" + i + "," + j + ")");
				}
			}
			System.out.println("Inner loop executed....");
		}
	}

	public static void main(String[] args) {
		doSomeLogic();
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop

 

Approach 3: With the help of a Boolean flag.

 

BreakOuterLoopDemo3.java

package com.sample.app.loops;

public class BreakOuterLoopDemo3 {

	public static void main(String[] args) {
		boolean flag = true;

		for (int i = 1; (i < 10 && flag); i++) {
			for (int j = 1; (j < 10 && flag); j++) {
				if (i * j > 5) {
					System.out.println("Breaking outer loop");
					flag = false;
				} else {
					System.out.println("(" + i + "," + j + ")");
				}
			}
			System.out.println("Inner loop executed....");
		}
	}

}

 

Output

(1,1)
(1,2)
(1,3)
(1,4)
(1,5)
Breaking outer loop
Inner loop executed....

 


 
 

You may like

Interview Questions

Extract the elements of specific type in a collection

Method overloading ambiguity with null values in Java

Quick guide to load balancers

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

No comments:

Post a Comment