This is a labelled loop, when break group_skip;
statement is executed, it will jump out of the do while loop which is labelled as group_skip
boolean isTrue = true;
outer: for (int i = 0; i < 5; i++) {
while (isTrue) {
System.out.println("Hello");
break outer;
} // end of inner while
System.out.println("Outer loop"); // does not print
} // end of outer loop
System.out.println("Good Bye");
This outputs
Hello
Good Bye
You can get the concept clear here.
- There is a labelled
for
loop called outer
and there is inner while
loop
- When inner for loop is being executed, it encounters
break outer;
statement
- The
outer for loop
has a System.out.println"Outer loop"
statement but that does not get printed.
- This is because
break outer
causes the control to jump out of labelled for
loop directly
Now this example for continue
statement
outer: for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println("Hello");
continue outer;
} // end of inner loop
System.out.println("outer"); // this won't print
} // end of outer loop
System.out.println("Good bye");
This prints
Hello
Hello
Hello
Hello
Hello
Good bye
- There is a labelled
for
loop here and an inner for
loop
- Inner
for
loop prints Hello
and continues to the outer
loop.
- Because of this, the statements below inner
for
loop are skipped and outer
loop continues to execute.
- At the end of
outer
for loop, Good Bye
is printed
Hope this makes everything clear.