Java Control Statements
- Java if Statement
- Java Nested if Statement
- Java if-else-if Statement
- Java Switch Case
- Java Switch with String
- Java Nested Switch
- Java Simple for Loop
- Java for each Loop
- Java Nested for Loops
- Java while loop
- Java continue Statement with for Loop
- Java continue in do-while Loop
- Java break to Exit a for Loop
- Java break with Nested Loops
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.
Control Statements
Java
Java Tutorial
Comments
Post a Comment