xyz xyz - 9 months ago 52
Java Question

How to break out from nested loop?

I have a method to compare two list of objects.

The objects are unique in both lists.

I doing it with 2 level nested for loops

I want to terminate the inner for loop's remaining cycles if two objects match correctly.

Is it possible to terminate the remaining iteration of a for loop in Java?!


The Sample Code:

public class NestedForLoops {

public static void main(String[] args) {
String one = "abcdefgh";
String two = "ijkhmnop";
System.out.println(nestedForLoop(one, two));


public static String nestedForLoop(String one, String two)
String res = "";
for(int i = 0; i < one.length(); i++)
for(int j = 0; j < two.length(); j++)
if(one.charAt(i) == two.charAt(j)){
System.out.println(i + " " + j);
res += one.charAt(i);
return res;



Break inner:

for (Object o1 : list1)
   for (Object o2 : list2)
        if (o1.equals(o2))

Break outer for loop:

outer: for (Object o1 : list1)
   for (Object o2 : list2)
        if (o1.equals(o2))
            break outer;