Java - Statement break Statement

What is break statement?

A break statement can exit from a block.

There are two forms of the break Statements:

  • Unlabeled break statement
  • Labeled break statement

An example of an unlabeled break statement is

break;

An example of a labeled break statement is

break label;

You can use use the unlabeled break statement inside switch, for-loop, while-loop, and do-while statements.

It transfers control out of a switch, for-loop, while-loop, and do-while statement.

For nested statements, an unlabeled break statement transfers control out of the inner statement. For example,

Demo

public class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 3; i++) {
      for (int j = 1; j <= 3; j++) {
        System.out.print(i + "" + j);
        if (i == j) {
          break; // Exit the inner for loop
        }//from   w  w w .  ja  v  a 2s  .co m
        System.out.print("\t");
      }
      System.out.println();
    }

  }
}

Result

Related Topics