The break statement

The break statement is used to terminate a loop or a switch / case statement. Normally, only the word break is used with a semi-colon after. This cancels the loop or the case statement in which the break statement is specified. This kind of statement is often used for example when looking for a specific value in a loop, and once it’s found we don’t want to continue to look for something that we already have. We just want to get out as quickly as possible.

Sometimes however there are situations where we find ourselves in a nested loop and want to cancel the outer loop from the inner one. For these situations it’s possible to mark the outer loop with a label to be able to tell the break statement which loop we want to break out from (if we break out from the outer loop we’ll of course automatically break out from the inner as well). A label is added just before the outer loop’s declaration followed by a colon. When you want to break out from it, write the break statement followed by the label.

The following two examples shows how to break out from a loop both without and with a label.

The output from the last example is:

Search for more Java info on this site here:
Custom Search

Please type any questions here.