Java Jump statements - break statement in Java Programming with examples

        After understanding the concepts of Loops in Java: for loop, while loop and do-while loop. It also becomes very much necessary to know how to alter the way of iteration during such looping statements or while using if-else statements. Suppose, you have to drive the loop until a specific condition and then exit it, when the inner condition becomes true, except the one(condition) that you passed in the loop declaration. 

For such conditions, Java provides us with 3 Jump statements: break, continue and return. Basically, we have used return so many times before, that its usage is pretty clear to everyone. That is, to return a particular value from a function, method or anything. In this tutorial, we'll mainly focus on break statement only.

Java break statement


In Java, the break statement has mainly 3 uses. Firstly, it can be used to exit a loop(whether it is for, while or do-while). Secondly, to terminate a statement sequence in the Java Switch statement(which we learnt in the previous tutorial). And third, break can also be used as a civilised form of goto statement

Whenever a break statement is encountered in  a loop, the loop is terminated and and all the statements in the loop body for all coming iterations are skipped and control moves to the next statement just next to the loop. Hence, it breaks the control flow of the whole loop, for a specified condition.

Syntax: break;

* break statement, most of the times is used with if statement, because it needs to check a condition for its execution most of the times.

Break with java for loop

The following code uses break along-with for loop to terminate execution when the 6th iteration is encountered.

public class breakStatementExample1 {

        public static void main(String[] args) {
      
            for(int i=1;i<=10;i++) {   
                System.out.println(i+"th iteration");
                if(i==6) {                    
                break;
               }
            }
        }
}

OUTPUT

1th iteration    
2th iteration
3th iteration
4th iteration
5th iteration
6th iteration

Here, a for loop iterates over the statements, telling it to execute the statements inside the loop for 10 times. But we applied break in if statement, that means whenever the particular condition in the if condition block becomes true. The break will terminate the whole loop.

The break statement can be used in every type of loop, even in case of infinite loops or nested loops also.

break with java while loop

public class breakStatementExample2 {
    public static void main(String[] args) {         int i=1;
        while(i<=10) {
                if(i==6break;
                System.out.println(i+"th iteration");
           i++;
            }
            }
}

OUTPUT

1th iteration    
2th iteration
3th iteration
4th iteration
5th iteration

Here, according to the arrangement of the statements. In the while loop body, it firstly checks whether i is equal to 6 or not, if it is equal to 6. Then break statement terminates the loop. Else the other statements continue to be executed until i doesn't become equal to 6.

break with java do-while loop

public class breakStatementExample3 {
public static void main(String[] args) {
    int i = 1;
    do {
    if(i==7break;
    System.out.println(i+"th iteration");
    i++;
    }while(i<=10);
   }
}

OUTPUT

1th iteration    
2th iteration
3th iteration
4th iteration
5th iteration
6th iteration

break with java nested loops

When one or more loops are used inside another loop, then this is known as nested loops.

When break statement is used in nested loops, it will only break out or terminate the innermost loop, depending upon where we applied break statement.
public class breakStatementExample4 {     public static void main(String[] args) {
        for(int i=1;i<=2;i++) {
            for(int j=1;j<=6;j++) {
                if(j==3break;
                System.out.println("Pass "+i+" : "+"["+j+"]"+"th iteration");
            }
            System.out.println();
        }
    }
}

OUTPUT 

Pass 1 : [1]th iteration
Pass 1 : [2]th iteration
Pass 2 : [1]th iteration
Pass 2 : [2]th iteration

Inside the inner loop, as soon as j becomes equal to 3. The inner loop breaks, without printing anything. But the outer loop remains un-affected and continues until its ending condition.

[ Note : Never use too many break statements in your program, otherwise this will lead to the destructuring of the code. ]

Using break as 'integrated' form of goto

[ goto is another jump statement which can be used to jump from anywhere to anywhere in a code/function/block/program. It is also known as unconditional jump statement ]

Java do not support goto statement, because it makes the code un-structuredly branched and maintaining such code becomes difficult. But still in some places, it is a valuable and legitimate construct for control flow. For this reason, Java extends the break statement as an integrated or dynamic form of goto. Where we can break out of any block of code irrespective of whether it is in a loop or not, using break statement just only with the help of labels.

Syntax: break label;

Label is simply a name given to a statement of a group of statements, marking that particular location with a name. 

Syntax :- labelName: 

The labelName can be any valid identifier but succeeding with a colon.

The label must contain a pair of curly braces, to signify which block belongs to which label. Thus to enclose the break statement for its proper functioning.

      label1: {  
        label2: { 
          System.out.println("Inside label 2");  
          break label2;
        }  
        System.out.println("Inside label 1");  
      }  

Program : 

public class breakStatementAsGoto{
public static void main(String[] args) {
     outer:{
        for(int i=0; i<3; i++) {  
               System.out.print("Pass " + i + ": ");  
                inner:{
                    for(int j=0; j<100; j++) {  
                        if(j == 10
                            break outer;  
                            System.out.print(j + " ");  
                      }  
                 System.out.println("This will not print");
              }  
          } 
    } 
            System.out.println("Last statement executed.");  
    }
}

OUTPUT

Pass 0: 0 1 2 3 4 5 6 7 8 9 Last statement executed.

We have made 2 labels outer and inner in the program. In the inner label or we can say inner loop, as soon as the value of j becomes 10, break will execute. Since, it is break outer, it will break the outer loop, instead of inner. Thus whole outer label block would be terminated and the statement next to it would be executed.

Also note, this will only work, if the break statement is inside the label block. Else it would not work. For example: 

public class breakError{
public static void main(String[] args) {
    mylabel1: for(int i=0; i<3; i++) {  
    System.out.print(i+"th turn");  
    }  
        for(int j=0; j<100; j++) {  
            if(j == 10break mylabel1; //Error
                System.out.print(j + " ");  
            }   
}
}

This code will show an error that the label 'mylabel1' is missing. Since, the break is not inside the mylabel1 label.


Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post