Wednesday 5 February 2014

Branching statement: break

The break Statement
We already seen the use of break in switch case. Similarly, break is used in while, do-while and for loops. Break has two forms in java.
   1. unlabelled break
   2. labelled break

unlabelled break
   Example
class BreakEx{
 public static void main(String args[]){
  for(int i=0; i < 10; i++){
   if(i==5) break;
   System.out.println(i);
  }
  System.out.println("I am out of the loop");
 }
}

Output
0
1
2
3
4
I am out of the loop
 
As you in the above program, when variable “i” reached to 5, break is called, and execution comes out of the loop

labelled break
   label is a group of statements, identified by using labelname.

Syntax
    labelName:{
      statement 1
      statement 2
      …....
      statement N
    }

Example
class BreakEx{
 public static void main(String args[]){
  myLoop: {
   for(int i=0; i < 10; i++){
    if(i==5) break myLoop;
    System.out.println(i);
   }
   System.out.println("I am also in label");
  }
  System.out.println("I am out of the loop"); 
 }
}
        
Output
0
1 
2
3
4 
I am out of the loop
 
As you see in the above program label name is myLoop. When variable 'i' value reaches to 5,  execution comes out of the label.




loops                                                 continue statement                                                 Home

No comments:

Post a Comment