Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Break Statement



The break statement is used to alter the flow of control inside loops and switch statements. We have already seen the break statement in action in conjunction with the switch statement. The break statement can also be used with while and for statements. Executing a break statement with any of these looping constructs causes immediate termination of the innermost enclosing loop.

The following diagram shows the diagrammatic explanation of the break statement.

Break statement

Example - Usage of break Statement in for loop

Following is an example of the break statement in a for loop−

Example.groovy

class Example {
   static void main(String[] args) {
      int[] array = [0,1,2,3];
		
      for(int i in array) {
         println(i);
         if(i == 2)
         break;
      }
   } 
}

Output

The output of the above code would be −

0 
1 
2 

As expected since there is a condition put saying that if the value of i is 2 then break from the loop that is why the last element of the array which is 3 is not printed.

Example - Usage of break Statement in while loop

Following is an example of the break statement in a while loop−

Example.groovy

class Example {
   static void main(String[] args) {
      int x = 10;

      while( x < 20 ) {
         if(x == 15){
            break;		 
         }	     
         x++;
         println("value of x : " + x );
      }
   }
}

Output

The output of the above code would be −

value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15

Example - Usage of break Statement in infinite loop

An infinite loop executes loop statements indefinitely. To stop the execution of an infinite loop, you can use the break statement inside a condition. When the program encounters the specified condition, the break statement terminates the loop.

In this example, we're showing the use of break statement to break an infinite loop using while loop. It will keep printing the numbers until the value of x becomes 15.

Example.groovy

class Example {
   static void main(String[] args) {
      int x = 10;

      while( true ) {
         println("value of x : " + x );
         x++;
         if(x == 15) {
            break;
         }
      }
   }
}

Output

The output of the above code would be −

value of item : 10
value of item : 11
value of item : 12
value of item : 13
value of item : 14
Advertisements