break statements

index
INTERMEDIATE

The syntax of a break statement is very simple:

break;

The break statement has two separate and distinct uses: exiting a loop, and exiting a switch statement. You cannot use a break anywhere but inside a loop or a switch statement.

Exiting a loop

Within any kind of a loop, break causes the loop to exit.

There is very little point in having a "bare" break that unconditionally exits a loop. Almost always, the break is embedded in an if statement. For example:

for (int i = 0; i < myArray.length; i++) {
    if (myArray[i] < 0) {
        System.out.println("Bad value in location " + i);
        break;
    }
}

In the case of nested loops, break exits the innermost loop.

Use of the break statement is discouraged. Basically, this is because it allows you to exit the loop in more than one way (the normal exit, plus any conditions that cause a break), which can be confusing; and it means that you may have to write additional code, after the loop, to figure out what the loop did. Hence, before you break out of a loop, you should try to find another way to get the same results.

Exiting a switch statement

The switch statement lets you choose which of several blocks of code to execute. Unfortunately, unless you put a break after each block of code, execution flows into the next block. For example:
switch (grade) {
    case 'A':
        System.out.println("You did great!");
        break;
    case 'B':
    case 'C':
    case 'D':
        System.out.println("You passed.");
    case 'F':
        System.out.println("You flunked!");
}

In the above code,

The requirement for break statements within a switch statement is widely regarded as poor language design, but it is consistent with C and many other older languages.

ADVANCED

You can exit multiple levels of loops and/or switch statements by using labels.