Monday, January 13, 2020

break statement

Break Statement


Generally, the break statements are inside the loop, the loop is instantly terminated and the control of the program resumes at the next statement following the loop. A break statement is used to exit from any block or conditional loop(for, while and do-while etc). The break statement is also used to terminate a case in switch-case clauses. There can be labeled or unlabeled break. An unlabeled break enables us to exit from the innermost block. A Labeled break can terminate any labeled statement.

break statement
break statement

Simple break example:


The control will exit from the labeled loop.

public class Demo {
     public static void main(String[] args) {
           for(int i=0;i<5;i++)
             {
              for(int j=0;j<5;j++)
              {
               System.out.print("*\t");
               if(i==j)
               break;
              }
              System.out.println();
             }
            }
}

Output:
*
* *
* * *
* * * *
* * * * *

Labels


Statements can be labeled to provide them some name by which they can be later referred. Labels can be used to uniquely identify the loops that are nested inside each other. Labels are generally used with break and continue.

Syntax

label_name: statement


labeled break java
labeled break


Labeled break example: 


Control with the labeled loop. 


public class Demo {
     public static void main(String[] args) {
           int i=5;
             out:for(;;)
             {
              for(int j=1;j<5;j++,i--)
              {
               System.out.print("*\t");
               if(i==j)
               break out;
              }
              System.out.println();
             }
            }
}


Output:
* * *

Video Tutorial