break/continue Statement
In Java, the break
and continue
statements are used to control the flow of loops.
break
Statement:
The break
statement is used to terminate the execution of a loop prematurely. When encountered inside a loop, it causes the loop to exit immediately, and the program continues with the statement following the loop.
Example using break
in a for
loop:
public class BreakStatementExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
if (i == 3) {
break; // Exit the loop when i equals 3
}
}
System.out.println("Loop terminated");
}
}
In this example, the output will be:
1
2
3
Loop terminated
Once the break
statement is encountered when i
is equal to 3, the loop is terminated, and the program continues with the statement following the loop.
continue
Statement:
The continue
statement is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration. It is often used to skip certain iterations based on a condition.
Example using continue
in a for
loop:
public class ContinueStatementExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the rest of the loop body for i equals 3
}
System.out.println(i);
}
System.out.println("Loop completed");
}
}
In this example, the output will be:
1
2
4
5
Loop completed
When i
is equal to 3, the continue
statement is encountered, and the rest of the loop body is skipped for that iteration. The program then continues with the next iteration.
Both break
and continue
statements are useful for controlling the flow of loops based on certain conditions. However, it's important to use them judiciously, as excessive use of break
and continue
statements can make the code less readable and harder to maintain.