Java

Break Statement In Java

The following two situations typically involve the usage of the break statement:

a) To exit the loop immediately, use the break statement. When a break statement is met inside a loop, the control exits the loop immediately, ending the loop for the remaining iterations. When a loop is utilized, it is combined with an if statement to ensure that the loop ends under a certain circumstance.

The crucial thing to remember is that only the inner loop is ended when a break statement is used inside a nested loop.

b) Switch case control also makes use of it. Typically, a break statement follows each case in a switch case so that future instances won’t be executed when the program control jumps to a case (see the example below). The control exits the switch-case body as soon as a break is found in the switch-case block.

Break sentence syntax: “break” word followed by a semicolon

break;

Example – Use of break in a while loop

The while loop in the example below runs from 0 to 100, but because there is a break statement that only executes when the loop value hits 2, the loop is ended and control is transferred to the statement that follows the body of the loop.

public class BreakExample1 {
   public static void main(String args[]){
      int num =0;
      while(num<=100)
      {
          System.out.println("Value of variable is: "+num);
          if (num==2)
          {
             break;
          }
          num++;
      }
      System.out.println("Out of while-loop");
  }
}

Output:

Value of variable is: 0
Value of variable is: 1
Value of variable is: 2
Out of while-loop

Example – Use of break in a for loop

You can see the same thing over here. The for loop is ended as soon as the var value reaches 99.

public class BreakExample2 {

   public static void main(String args[]){
	int var;
	for (var =100; var>=10; var --)
	{
	    System.out.println("var: "+var);
	    if (var==99)
	    {
	         break;
	    }
	 }
	 System.out.println("Out of for-loop");
   }
}

Output:

var: 100
var: 99
Out of for-loop

Example – Use of break statement in switch-case

public class BreakExample3 {

   public static void main(String args[]){
	int num=2;
	      
	switch (num)
	{
	    case 1:
	       System.out.println("Case 1 ");
	       break;
	    case 2:
	       System.out.println("Case 2 ");
	       break;
	    case 3:
	       System.out.println("Case 3 ");
	       break;
	    default:
	       System.out.println("Default ");
	}
   }
}

Output:

Case 2

Because the next case block would otherwise execute without a break statement, we have one in this example after each case block. Without a pause, the identical program’s result would be

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button