System.out.println ("starting loop:");
for (int n = 0; n < 7; ++n)
{
System.out.println ("in loop: " + n);
if (n == 2) {
continue;
}
System.out.println (" survived first guard");
if (n == 4) {
break;
}
System.out.println (" survived second guard");
// continue at head of loop
}
// break out of loop
System.out.println ("end of loop or exit via break");
This will lead to following output:
starting loop:
in loop: 0
survived first guard
survived second guard
in loop: 1
survived first guard
survived second guard
in loop: 2
in loop: 3
survived first guard
survived second guard
in loop: 4
survived first guard
end of loop or exit via break
You can label a block, not only a for-loop, and then break/continue from a nested block to an outer one. In few cases this might be useful, but in general you'll try to avoid such code, except the logic of the program is much better to understand than in the following example:
first:
for (int i = 0; i < 4; ++i)
{
second:
for (int j = 0; j < 4; ++j)
{
third:
for (int k = 0; k < 4; ++k)
{
System.out.println ("inner start: i+j+k " + (i + j + k));
if (i + j + k == 5)
continue third;
if (i + j + k == 7)
continue second;
if (i + j + k == 8)
break second;
if (i + j + k == 9)
break first;
System.out.println ("inner stop: i+j+k " + (i + j + k));
}
}
}
Because it's possible, it doesn't mean you should use it.
If you want to obfuscate your code in a funny way, you don't choose a meanigful name, but http: and follow it with a comment, which looks alien, like a webadress in the source-code:
http://stackoverflow.com/questions/462373
for (int i = 0; i < 4; ++i)
{
if (i == 2)
break http;
I guess this is from a Joshua Bloch quizzle. :)