Java break and continue

Java’s break and continue statements are used to alter the flow of control.

break The break statement can be used in for, while or do-while loops. It is also used in switch structure. A break statement exits the loop without executing the rest of the code in the loop. In other words, if the program encounters a break inside a for loop, it exits the loop without executing the remaining statements even if the test condition of the loop is still valid.

continue The continue statement can be used in for, while, and do-while loops. A continue statement skips the rest of the code in the loop and moves on to the next iteration. So, when the program encounters a continue statement inside a for loop, it will skip the remaining statements and simply move on the next iteration.

Example

public class BreakAndContinue {
    public static void main(String args[]) {

    for (int count = 1; count <= 10; count++) {
        if (count == 6) {
            break; // break out of the loop
        }
        System.out.println(count);

    for (int count = 1; count <= 10; count++) {
        if (count == 6) {
            continue;  
            // skip remaining code this time but continue looping
        }
        System.out.println(count);
    }
}
Technologies: