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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
Class Find{ public static void main(String args[]) { int arr[] = {1,2,3,4,5,6,7}; boolean found = false; for(int i = 0; i<arr.length; i++) { if(arr[i]== 5) { found = true; break; } } if(found) {System.out.println(“5 is found”); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
Class Find{ public static void main(String args[]) { int arr[][] = {{1,2,3},{4,5,6,}}; boolean found = false; find: for(int i = 0; i<arr.length; i++) { for(int j=0; j<arr[i].length;j++) if(arr[i][j] == 5) { found = true; break find; //terminates outer for loop } } if(found) {System.out.println(“5 is found”); } } |
Output:
5 is found |
In this case, the break statement terminates the outermost ‘for’ loop which is labeled.