Groovy – Break Statement

  • Post author:
  • Post category:Groovy
  • Post comments:1 Comment

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 statements

Following is an example of the break statement −

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

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.

Next Topic:-Click Here

This Post Has One Comment

Leave a Reply