Java Reference
In-Depth Information
System.out.println("Break out of y loop.\n");
break; // new break statement
}
}
}
System.out.println("\nBreak with No Label:");
outer: // new label
for (int x = 0; x < 3; x++) {// outer loop (x loop)
for (int y = 0; y < 3; y++) { // inner loop (y loop)
System.out.println("x = " + x + " and y = " + y);
if (x == y) { // same conditional expression
System.out.println("Break out of both loops.\n");
break outer; // new break statement with label
}
}
}
}
}
9. Save the class by clicking the disk icon or selecting File, then Save.
10. Run the application by clicking the green play icon or selecting Run, and then Run.
How It Works
Now take a look at how it works.
1. The application begins by executing the main method, which in this case is the only method.
2. The first statement outputs a line of text to the console indicating that the first set of for loops are
being executed. They do not include any break statements.
3. The nested for loops iterate through nine times. During each iteration, the current values for x
and y are printed to the console. This is how a standard nested for loop iterates: First, in the outer
loop, x = 0 and the inner loop will iterate for y = 0 , y = 1 , and y = 2 . When y = 3 , the condi-
tional expression on the inner for loop (3 < 3) will evaluate to false , so the inner for loop ends
and the outer for loop iterates to x = 1 . Again, the inner for loop will iterate for y = 0 , y = 1 ,
and y = 2 . When y = 3 , the conditional expression is false again and the inner loop ends. The
outer for loop iterates again to x = 2 , and the inner for loop cycles through three values for y
again. Finally, when x = 3 , the conditional expression on the outer for loop will be evaluated as
false and both for loops will end. You can see each of these iterations printed to the console.
4. Another statement is then printed to the console, indicating that the second set of for loops will be
executed with a break statement. The program proceeds to the next nested for loops.
5. The second set of nested for loops iterates through only six times. During each iteration, the cur-
rent values for x and y are printed to the console. When the break statement is encountered,
another line is output to the console indicating the break. This is how nested for loops with a
break statement iterate: First, in the outer loop x = 0 and in the inner loop y = 0 . These values
are printed to the console and then the program checks if x equals y . Since 0 == 0 is true , there is
a line printed to the console and the break occurs. This breaks from the inner loop and proceeds to
the next outer loop iteration. In the outer loop x = 1 and in the inner loop y = 0 again; these are
Search WWH ::




Custom Search