Academic Java    Java Tutorial  >  Statements  >  break, continue (a)

break, continue Example

Java break, continue EXAMPLE output This program contains two separate loops, one with a continue statement, the other with a break statement.

The continue statement when executed causes the first loop to immediately begin a new iteration.

The break statement when executed causes an immediate jump out of the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Break Continue Statement Example
class BreakContinueStatementExample {

   public static void main(String[] args) {

      System.out.print("loop 1: ");
      for(int i=0; i < 10; i++) {

         if(i % 2 == 0) continue; // ignore even numbers
         System.out.print(i);

      }

      System.out.print("\nloop 2: ");
      for(int i=0; i < 10; i++) {

         if(i == 5) break; // break out of the loop
         System.out.print(i);

      }

   }

}

9 In this first loop, if the value of i is even (recall that % is the remainder operator) the condition is true.
This causes continue to be executed.
A continue statement causes the loop to begin a new iteration starting with the loop's condition test.

17 In this second loop, if i has the value 5 then the condition is true and break is executed.
This causes an immediate jump out of the loop.