In Java, break
and continue
are two control flow statements that are used within loops to change the normal execution of the loop.
break
is used to terminate the enclosing loop or switch statement and transfer control to the statement immediately following the loop or switch. When break
is encountered inside a loop, the loop is immediately terminated and control passes to the statement following the loop. The syntax of the break
statement is as follows:
break;
Here’s an example of using break
to terminate a loop when i
equals 5
:
for (int i = 1; i <= 10; i++) { if (i == 5) { break; // exit the loop if i equals 5 } System.out.println("The value of i is " + i); }
In this example, the loop runs from 1
to 10
, but as soon as i
equals 5
, the break
statement is executed and the loop terminates. The output of this code is:
The value of i is 1 The value of i is 2 The value of i is 3 The value of i is 4
continue
: When used inside a loop, the continue
statement causes the current iteration of the loop to be skipped and control to be transferred to the next iteration of the loop. This can be useful for skipping over certain iterations of a loop based on a certain condition. The syntax of the continue
statement is as follows:
continue;
Here’s an example of using continue
to skip over the iteration where i
equals 5
:
for (int i = 1; i <= 10; i++) { if (i == 5) { continue; // skip the rest of the loop body if i equals 5 } System.out.println("The value of i is " + i); }
In this example, the loop runs from 1
to 10
, but when i
equals 5
, the continue
statement is executed and the rest of the loop body is skipped.