Java break Statement With Examples

Sometimes you may need to continue to the next iteration with in the loop with out executing the statements or you may need to terminate the loop altogether. For these two scenarios Java provides two control statements- continue and break. In this post we’ll go through Java break statement in detail along with usage examples.

Break statement in Java

break statement in Java has the following three uses-

  1. Exiting a loop– When the break statement is encountered with in a loop, the loop is terminated and the control transfers to the statement immediately following the loop.
  2. In switch statement– break statement is used to terminate the switch statement too.
  3. Used with label to work as “goto” statement– You can use labelled break statement to exit out of the labelled block.

Java break statement examples

Here are some examples showing the usage of break statement to exit a loop. Generally break statement is used with if-else statement.

1- Using break statement to come out of infinite while(true) loop.

With in an infinite while(true) loop you can keep a condition which terminates the loop when the condition evaluates to true.

Output

2- Using break statement with for loop.

Output

3- Using break statement with nested loops.
When break statement is used with nested loops it exits the loop in whose scope it is used.

Output

Here break statement is used in the scope of the inner loop so it breaks out of that for loop when value of j is 5 in each iteration.

In the next example break statement is used with in the scope of the outer for loop so it breaks out of that loop.

Output

Java labelled break statement

Labelled break statement helps you to come out of deeply nested loops. With a normal break statement even in nested loop you can break out of a single loop which is in scope. With labelled break statement you can exit more than one block of codes or loops only requirement is that the label must enclose the break statement.

For labelling a block of code you just put a label (any name) in the starting of the block followed by a colon. To break out of that label you will use the following statement.

Java labelled break statement examples

In the code a label named outer is used with the outer for loop.
When break outer; statement executes it exits out of the scope of the labelled statement.

Output

You don’t necessarily need loops to use labelled break statement, you can label a block of code and use break statement with label to break out of those labelled blocks.

Output

That’s all for the topic Java break statement With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.