The break
and continue
statements are control statements in Java that are used to alter the flow of execution of a loop.
The break
statement is used to exit a loop or switch statement and transfer control to the statement immediately following the loop or switch. It can be used in while
, do-while
, for
, and switch
statements.
Here is an example of how to use the break
statement in a while
loop:
int i = 0; while (true) { if (i == 5) { break; // exit the loop when i is 5 } System.out.println("i = " + i); i++; }Source:www.lautturi.com
In this example, the while
loop will run indefinitely because the condition is always true
. However, the break
statement is used to exit the loop when i
is 5. The output will be:
i = 0 i = 1 i = 2 i = 3 i = 4
The continue
statement is used to skip the rest of the current iteration of a loop and start the next iteration. It can be used in while
, do-while
, and for
loops.
Here is an example of how to use the continue
statement in a for
loop:
for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; // skip the rest of the current iteration when i is even } System.out.println("i = " + i); }
In this example, the for
loop iterates 10 times, but it skips the rest of the current iteration when i
is even. The output will be:
i = 1 i = 3 i = 5 i = 7 i = 9
Both the break
and continue
statements are useful for controlling the flow of execution of a loop and can be used to solve specific problems in your code. However, they should be used sparingly as they can make your code harder to read and understand.