AP Computer Science --- Haas --- BreakAndContinue

The break and continue statements can be used in for or while loops.

When a program encounters a break inside a loop, it exits the loop without executing the remaining statements even if the test condition of the loop is still valid.

When a program encounters a continue statement inside a loop, it skips the rest of the code in the loop and moves on to the next iteration.

Copy and run the following in BlueJ. Try to predict the output before you run it.



/**
 * Examples of break and continue
 */
public class BreakAndContinue {
    public static void main(String args[])
    {
        for (int count = 1; count <= 10; count++) {
            if (count == 6)
            {
                break; 
            }
            System.out.println(count);
        }
        
        for (int count = 1; count <= 10; count++) {
            if (count == 6)
            {
                continue;  
            }
            System.out.println(count);
        }
    }

}


/**
 * Example of nested break
 */
public class NestedBreak {
    public static void main(String args[])
    {
        for (int i = 1; i < 4; i++)  {
            System.out.print("Line: " + i + " = ");
            for (int count = 1; count <= 10; count++) {
                if (count == 6)  {
                    break; 
                }
                System.out.print(count);
            }
            System.out.println();
        }
    }
}