Break statement in Java

Break keyword is used in three main situations:

  1. Inside switch statement
  2. To break out of any loop.
  3. As a civilized form of goto statement.

1. Breaking out of switch statement

When a case statement inside a switch is done and you don’t want to execute any other case, you use break to terminate out of the switch statement.

The output is:

In the example above, since grade was ‘C’ , case ‘C’ matches then Feedback: Average! is printed and on encountering break the switch terminates. No more cases are tested.


2. Breaking out of any loop

break with loops is often used along with if-statement, i.e. if some conditions have been met then break the loop. Like in the example below, as soon as the key is found, the loop breaks.

Output is :

Here, the for loop has been used for the demonstration but it could have been any one of the for, for-each, while or do-while loop.

breaking out of inner-loops

When break is used with nested loops, it only breaks the inner-most loop like in the example below:

The output is:

Miscellaneous

If a loop surrounds a switch statement then break inside switch statement only affects that switch and not the enclosing loop.

Similarly, if a switch statement surrounds a loop then the break inside loop only affects that loop and not the enclosing switch statement.


3. Mimicking goto statement in Java

Java doesn’t support GOTO statement because it makes the code non-linear and hard to maintain.

But you can still mimick GOTO in a civilized way using break with labels, like in :

The label can be a label of any block of code, a loop, or a compound statement. But this block must enclose the break statement.

A label is any Java identifier followed by a colon. To label a block put the label name before the block of code.

You can use this strategy to break out of any set of nested loops or blocks using single break.

Example: Breaking out of Nested blocks

In the example below, a single break takes the control out of the three nested blocks:

The output is :

Example: Breaking out of Nested loops

break with label can also be used to break out of the nested loops:

The output is :

Note that in all the cases the target label of break encloses that break.

Caution:

You cannot break out to any label, you can break out only to those labels which suround that break. For example the code below is invalid.

It will throw a compile time error because the label second where we want to break out, doesn’t enclose this break.