Java Break and Continue

Java Break

We have already discussed break in switch statement topic. In switch statement break is used to stop execution of switch statement and to shift the execution control to next statement to switch.
break keyword is also used to stop execution of a loop.

Java break Example

Following example stops the loop when the value of i becomes equal to 5:


for (int i = 0; i < 6; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}

Java Continue

The break keyword break the complete execution of loop or switch statement while continue keyword skips remaining statements of loop within the curently executing iteration.

Java continue Example

Following example will skip the print statement when value of i equals 5:

for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}

break and continue can also be used in while and do/while loop as we have used in for loop.

Java while break example

Following example will stop the execution of while loop when the value of i becomes 10:

int i = 0;
while (i < 20) {
System.out.println(i);
i++;
if (i == 10) {
break;
}
}

Java while continue example

Following example will skip the print statement when the value of i becomes 10:


int i = 0;
while (i < 20) {
if (i == 10) {
i++;
continue;
}
System.out.println(i);
i++;
}