Friday, February 13, 2015

While Loop With Break and Continue

This section exlains about While loop with break and continue, the below example explains how the flow is affected with the usage of break/continue.


package Example1;

public class WhileLoopWithBreak {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int j=0;
  while(j<=10){
   System.out.println(j);
   j++;
   if(j==5){
    System.out.println("its five");
    if(j%5==0){
     break;
    }    
   }
  }
 }
}

output:
0
1
2
3
4
its five



package Example1;

public class WhileLoopWithContinue {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int j=0;
  while(j<=10){
   System.out.println(j);
   j++;
   if(j==5){
    System.out.println("its five");
    if(j%5==0){
     continue;
    }    
   }
  }
 }
}

output:
0
1
2
3
4
its five
5
6
7
8
9
10

When break is used it total comes out of all the loops while continue break the existing loop and continue from the beginning of the loop. >>>ForLoop
------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment