Break
statement is one of the different control statements which we use very often. If break statement is found in loop, it will exit the loop and execute the statement following the loop.
Table of Contents
Java break statement example
You want to search for the element in an array and if element is found, exit the loop.
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 |
package org.arpit.java2blog; public class BreakStatementExample { public static void main(String[] args) { BreakStatementExample bse=new BreakStatementExample(); int arr[] ={32,45,53,65,43,23}; bse.findElementInArr(arr, 53); } public void findElementInArr(int arr[],int elementTobeFound) { for (int i = 0; i < arr.length; i++) { if(arr[i]==elementTobeFound) { System.out.println(elementTobeFound+" is present in the array "); break; // break statement is encounter, control will exit current loop now } } System.out.println("Executing statments following the loop"); } } |
When you run above program, you will get below output:
Executing statments following the loop
Labeled break statement:
Labeled break statement is used when you want to break labeled for loop.
For example:
You want to find an element in two-dimensional array. Once you got the element in the array, exit the outer loop.
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 |
package org.arpit.java2blog; public class LabeledBreakStatementExample { public static void main(String[] args) { LabeledBreakStatementExample bse = new LabeledBreakStatementExample(); int arr[][] = { { 32, 45, 35 }, { 53, 65, 67 }, { 43, 23, 76 } }; bse.findElementInArr(arr, 65); } public void findElementInArr(int arr[][], int elementTobeFound) { outer: for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] == elementTobeFound) { System.out.println(elementTobeFound + " is present in the array "); break outer; // labeled break statement is encountered, control will exit // outer loop now } } } System.out.println("Executing statements following the outer loop"); } } |
When you run above program, you will get below output:
Executing statements following the outer loop
Switch Case:
You can also use break statement in switch case. Once case condition is met, you will exit the switch case.
For example:
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 |
package org.arpit.java2blog; public class SwitchCaseExample { public static void main(String[] args) { char vehType = 'C'; switch(vehType) { case 'B' : System.out.println("BUS"); break; case 'C' : System.out.println("Car"); break; case 'M' : System.out.println("Motor cycle"); default : System.out.println("Invalid vehicle type"); } System.out.println("Your vehicle type is " + vehType); } } |
When you run above program, you will get below output:
Your vehicle type is C
That’s all about Java break statement example.