logo codesdope

Break and Continue in Java


In the last topic, we learned about loops which are used to repeat a certain process some number of times.

What if we can control the way our loop operates.

In Java, we can jump out of a loop or jump to the starting condition of a loop whenever we want. We do this with the help of break and continue statements respectively.

break


break is used to break or terminate a loop whenever we want.

Just type break; after the statement after which you want to break the loop. As simple as that !

Remember, we had also used break statements in switch..case in the previous topic.

Consider an example.

class Co1{
public static void main(String[] args){
  int n;
  for(n = 1; n <= 5; n++){
    System.out.println("*");
    if(n == 2){
      break;
    }
  }
}
}
Output
*
*

In the above example, after the first loop executes and '*' gets printed, n++ increases the value of 'n' to 2. Again '*' gets printed and since the condition of if satisfies, break; gets executed and the loop terminates.

Let's have a look at one more example of break.

import java.util.*;

class Co2{
public static void main(String[] args){
  int x;
  Scanner s = new Scanner(System.in);

  for(;;){
    System.out.println("Enter 0 to stop");
    x = s.nextInt();
    if (x == 0){
      break;
    }
  }
}
}
Output
Enter 0 to stop
3
Enter 0 to stop
32
Enter 0 to stop
23
Enter 0 to stop
0

This is an infinite loop. To terminate this, we are using break. If the user enters 0, then the conditon of if will be satisfied and break will be executed and the loop will be terminated.

continue


The continue statement works similar to break statement. The only difference is that break statement terminates the loop whereas continue statement passes control to the conditional test i.e. where the condition is checked.

In short, it passes control to the nearest conditional test in do...while loop, or while statement in which it exists in while loop, or for in for statements skipping the rest of the statements in the loop.

class Co3{
public static void main(String[] args){
  int n = 1;
  do {
    if( n == 5){
      n = n + 1;
      continue;
    }
    System.out.println("n = " + n);
    n++;
  } while( n < 10 );
}
}
Output
n = 1
n = 2
n = 3
n = 4
n = 6
n = 7
n = 8
n = 9

In the above example, notice that n = 5 is not printed because as the value of 'n' becomes 5, the if condition becomes true and the statements in the body of if get executed. Thus n = n+1 increases the value of 'n' to 6 and continue statement passes the control to the test condition and rest of the statements are not executed ( System.out.println("n = " + n); n++; - these two statements are not executed when n is 5 ).Then again the iteration starts and the numbers get printed from 6 onwards.

Winning doesn't come cheaply. You have to pay a big price.
-Jeev Milkha Singh

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.