Monday 11 May 2015

Break statement in Java

The break statement has two forms: labeled and unlabeled.

Unlabeled Break statement :This form of break statement is used to jump out of the loop when specific condition occurs. This form of break statement is also used in switch statement.

break statement can be used in the following cases.

1. inside switch to stop fall-through. (Unlabeled )
2. Inside loops to break loop based on some condition. (Unlabeled )
3.Inside labeled blocks to break block execution based on some condition. (Labeled )

Examples:

package in.blogspot.java2bigdata;
public class LabelTest {
  
   public static void main(String[] args) {
    int x = 10;
    Label1:{
     System.out.println("label one");
     if(x==10)
      break Label1;
    }
     
 }
}
  

package in.blogspot.java2bigdata;
public class LoopTest {
  
   public static void main(String[] args) {
  
    for(int loopNumber= 1;loopNumber<10;loopNumber++){
     if(loopNumber==9)
      break;
     System.out.println(loopNumber);
    }
     
 }
}

switch statement example Click here.

If we are using any where else we will get compile time error: break can not be used outside of a loop or a switch.

No comments:

Post a Comment