Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to break outer loop in Java?

Given below function, Interviewer wants me to break the outer loop.

         private Static Void print() {
                  for (int i = 0; i
                           for (int j = 0; j
                                    System.out.println(i + " " + j);
                                    if (i * j > 10) {
                                             break;
                                    }
                           }
                  }
         }

There are couple of ways to do this.

Way 1: Use a flag to come out of outer loop

Application.java
package com.sample.app;

public class Application {

private static void print() {
boolean flag = false;
for (int i = 0; i 10; i++) {
for (int j = 0; j 10; j++) {
System.out.println(i + " " + j);
if (i * j > 10) {
flag = true;
break;
}
}

// Breaking outer loop
if (flag)
break;
}
}

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

Way 2: You can use labels to come out of outerloop.

Application.java
package com.sample.app;

public class Application {

private static void print() {
outerLoop: for (int i = 0; i 10; i++) {
for (int j = 0; j 10; j++) {
System.out.println(i + " " + j);
if (i * j > 10) {
break outerLoop;
}
}
}
}

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

You may like
Interview Questions
Programming Questions
Miscellaneous
Threads: print characters of a string simultaneously
Why Java compound assignment operators do not require casting?
Can I call one constructor from another in java?
Implement Runnable vs extends Thread
How to create immutable list in Java?
Open-closed principle design problem


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

How to break outer loop in Java?

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×