How to use break and continue statements in Java?



The break statement in Java programming language has the following two usages −

  • When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
  • It can be used to terminate a case in the switch statement (covered in the next chapter).

Syntax

The syntax of a break is a single statement inside any loop −

break;

Example

Live Demo

public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
            break;
         }
         System.out.print( x );
         System.out.print("
");       }    } }

Output

This will produce the following result −

10
20

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

  • In a for loop, the continue keyword causes control to immediately jump to the update statement.
  • In a while loop or do/while loop, control immediately jumps to the Boolean expression.

Syntax

The syntax of a continue is a single statement inside any loop −

continue;

Example

Live Demo

public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         if( x == 30 ) {
            continue;
         }
         System.out.print( x );
         System.out.print("
");       }    } }

Output

This will produce the following result −

10
20
40
50

Advertisements