x

Java – Break statement

PREV     NEXT

Java Break statement:


When a program executes a break statement, then the loop (for/switch/while/do while) which contains the break statement is terminated. The flow of the execution jumps to the outside of the loop.

Example for Java Break statement:

Output:

5 is found

In the above program the for loop iterates over the elements of the array ‘arr’. When the element 5 is present in the array, then a boolean flag ‘found’ is set to true and immediately the for loop is terminated. Thus the next if block followed by the for loop is executed.

There are two types of break statements


  • Labelled break
  • Unlabeled break

Unlabeled break is the one explained above.

The difference between the labelled and unlabeled break is that, unlabeled break terminates the innermost switch,for,while,do while loop which contains the break statement and labeled break terminates the outer loop which is labeled.

Example:

Consider the same example searching an element over a two dimensional array.

Output:

5 is found

In this case, the break statement terminates the outermost ‘for’ loop which is labeled.

PREV     NEXT



Like it? Please Spread the word!