Introduce Java Break and Continue and give examples
break
KeywordThe break
keyword is used to terminate a loop or switch statement prematurely. The basic syntax is as follows:
break; // for loops
break label; // for labeled blocks
break
is encountered within a loop (like for
, while
, or do-while
), it immediately terminates the loop, and the control moves to the statement following the loop.switch
statement, break
is used to exit the case block, preventing the execution from falling through to subsequent cases.switch
statement to prevent fall-through behavior.public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
System.out.println(i);
}
System.out.println("Loop terminated.");
}
}
Output:
1
2
3
4
Loop terminated.
continue
KeywordThe continue
keyword is used to skip the current iteration of a loop and proceed to the next iteration. The basic syntax is:
continue; // for loops
continue label; // for labeled blocks
continue
is encountered, the remaining code in the loop body is skipped, and control jumps to the next iteration of the loop.public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skips the even numbers
}
System.out.println(i);
}
System.out.println("Loop completed.");
}
}
Output:
1
3
5
7
9
Loop completed.
break
and continue
break
terminates the loop entirely, while continue
skips the current iteration and proceeds with the next one.break
when you want to exit a loop based on a condition. Use continue
when you want to skip specific iterations but continue looping.break
, the program execution continues with the next statement after the loop. After continue
, execution jumps to the loop's next iteration.In summary, break
and continue
are essential keywords in Java for controlling loop execution. Understanding their syntax, usage, and scenarios helps in writing effective and efficient code. Use break
to exit loops and continue
to skip iterations based on conditions, enhancing the control flow in your programs.