Break is a java keyword used to change the current program execution flow. There are two forms of break statements available: labeled and unlabeled statements. We can use break statement to terminate either a loop (for, while, do-while) or switch statement.

BREAK KEYWORD

Basic syntax 

Syntax of the break statement is shown below.

break;

Using break statement to terminate loop (unlabeled statement)

Example usage of break statement with unlabeled form is as shown below. Here, loop will be terminated once the value of integer variable is greater than 10.

If break statement is used inside a loop, which is present within another loop, inner most loop (immediate loop after break statement) is terminated upon execution of break statement.

public class BreakExample {
 public static void main(String args[]){
  int i;
  for(i=0; i<15; i++) {
   if(i > 10) {
      break;
   }
  }
  System.out.println("Value of i after break::" + i);
 }
}

Output of the program is shown below.

Value of i after break::11

Using Break statement to terminate switch statement

Below program shows how to use break statement inside switch statement. Here, after on each case, i value is evaluated and if a match is found, switch statement is terminated. Otherwise, execution of switch statement continues. The output of the following program will be “i is 0“, as variable i is initialized with value 0.

public class BreakExample {
	public static void main(String args[]){
		int i = 0;
		switch(i)
		{
			case 0: 
				System.out.println("i is 0");
				break;
			case 1: 
				System.out.println("i is 1");
				break;
			case 2: 
				System.out.println("i is 2");
				break;
			default:
				System.out.println("i is more than 2");
		}
	}
}

Using break statement to terminate loop (labeled statement)

Following example shows usage of labeled break statement. Here, if the integer variable find is present in the array, loop will be terminated and the position of the element in the array is printed on the console output.

public class BreakExample {

	public static void main(String args[]){
		
		int[][] array = {{ 2, 3, 35}, { 12, 10, 20}, { 22, 18, 7}};
		int find = 18;
	        int i,j =0;
	        boolean numberSearched = false;

	    out: for (i = 0; i < array.length; i++) {
	            for (j = 0; j < array[i].length; j++) {
	                if (array[i][j] == find) {
	                    numberSearched = true;
	                    break out;
	                }
	            }
	         }

	        if (numberSearched) {
	            System.out.println("Number " + find + " is present!! at : {" + i + ", " +j+"}");
	        } else {
	            System.out.println(find + " not in the array");
	        }
	}
}

Output

Number 18 is present!! at : {2, 1}

In this article, we learned about break statement with labeled and unlabeled format and it’s usage with switch and loop statements.

You might be interested in following topics.