Java Break Statement

This article explains break statement in Java.

Break statement

 

The break statement can be used in 3 ways :
– Break is used to exit a loop
– Break is used to terminate a statement sequence in a switch statement
– Break can be used in nested blocks to go to the end of a block.

Break to exit a loop

 

Here is an example if break statement to exit a loop :

 

int[] arr = {10,20,30,40,50};
    
    for(int element : arr){
      System.out.println(element);
      if(element == 30)
        break;
    }

 

Without the break, the loop should have iterated over all elements. But the break statement forces to exit the loop when iterator element is 30.
 
The output of above program is :
0
20
30

Break to come out of switch statement sequence

 

Here is an example of using switch statement to exit statement sequence in a switch statement.

 

int month = 5;
    
    switch(month){
    case 12:
    case 1:
    case2:
      System.out.println("Winter");
      break;
    case 3:
    case 4:
    case 5:
      System.out.println("Spring");
      break;
    case 6:
    case 7:
    case 8:
      System.out.println("Summer");
      break;
    case 9:
    case 10:
    case 11:
      System.out.println("Autumn");
      break;
    }

 

The above program prints the season name for the month number provided.

 

If the break statements are removed, the program will print :
 
Spring
Summer
Autumn

 

This is because after a match is found in case 5, control flows through rest of the statements.

 

Break statement helps prevent this. With break statement, the program prints :
Spring

 

Using labelled break to go to end of a block

 

break statements can be used to go to the end of a block, by using a label name given to it.

 

Here is the syntax :

 

break label;
 
Here label represents the name of the block.

 

Here is an example of this :

 

boolean flag = true;
    block1: {
      System.out.println("Inside Block 1");
      block2: {
        System.out.println("Inside Block 2");
        if (flag)
          break block1;
        System.out.println("Leaving Block 2");
      }
      System.out.println("Leaving Block 1");
    }
    System.out.println("Outside block1");
  }

 

The break block1 statement takes the control to the end of block1.
 
Here is the output of this program :

 

Inside Block 1
Inside Block 2
Outside block1

 

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags