Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I break out of nested loops in Java?

I've got a nested loop construct like this:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break; // Breaks out of the inner loop
}
}
}

Presently how might I break out of the two loops? I've looked at comparable inquiries, yet none concerns Java explicitly. I was unable to apply these arrangements in light of the fact that most utilized gotos
I would prefer not to place the inward loop in an alternate technique.

I would prefer not to rerun the loops. When breaking I'm done with the execution of the loop block.
by

2 Answers

sandhya6gczb
To break out of the nested loop in Java use a labeled break statement.

class LabeledBreak {
public static void main(String[] args) {

// name the loop as first
first:
for( int i = 1; i < 10; i++) {

// name the loop as second
second:
for(int j = 1; j < 5; j ++ ) {
System.out.println("i = " + i + "; j = " +j);


if ( i == 3)
break first;
}
}
}
}



In the above example break first is used to terminate the loop and control goes to the line after first loop.
Sonali7
A named block can be used to overcome this situation:
search: {
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break search;
}
}
}
}

Login / Signup to Answer the Question.