Java break Statement with Nested Loops Example



This Java example demonstrates how to use a break statement inside the nested loops in Java with an example.

Using break with Nested Loops

When break keyword used inside a set of nested loops, the break statement will only break out of the innermost loop. 
For example:
package net.javaguides.corejava.controlstatements.loops;

public class BreakWithNestedLoops {
    public static void main(String args[]) {
        for (int i = 0; i < 3; i++) {
            System.out.print("Pass " + i + ": ");
            for (int j = 0; j < 100; j++) {
                if (j == 10)
                    break; // terminate loop if j is 10
                System.out.print(j + " ");
            }
            System.out.println();
        }
        System.out.println("Loops complete.");
    }
}
Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 
Pass 1: 0 1 2 3 4 5 6 7 8 9 
Pass 2: 0 1 2 3 4 5 6 7 8 9 
Loops complete.
As we can see, the break statement in the inner loop only causes termination of that loop. The outer loop is unaffected.

Comments