Java Tutorial/Statement Control/Break Statement

Материал из Java эксперт
Перейти к: навигация, поиск

Breaking Indefinite Loops

public class MainClass {
  public static void main(String[] args) {
    OuterLoop: for (int i = 2;; i++) {
      for (int j = 2; j < i; j++) {
        if (i % j == 0) {
          continue OuterLoop;
        }
      }
      System.out.println(i);
      if (i == 107) {
        break;
      }
    }
  }
}



2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107


Labelled breaks breaks out of several levels of nested loops inside a pair of curly braces.

public class Main {
  public static void main(String args[]) {
    int len = 100;
    int key = 50;
    int k = 0;
    out: {
      for (int i = 0; i < len; i++) {
        for (int j = 0; j < len; j++) {
          if (i == key) {
            break out;
          }
          k += 1;
        }
      }
    }
    System.out.println(k);
  }
}





The break Statement

  1. The break statement is used to break from an enclosing do, while, for, or switch statement.
  2. It is a compile error to use break anywhere else.
  3. "break" breaks the loop without executing the rest of the statements in the block.

For example, consider the following code



public class MainClass {
  public static void main(String[] args) {
    int i = 0;
    while (true) {
        System.out.println(i);
        i++;
        if (i > 3) {
            break;
        }
    }
  }
}



The result is

0
1
2
3


The Labeled break Statement

  1. The break statement can be followed by a label.
  2. The presence of a label will transfer control to the start of the code identified by the label.
  3. For example, consider this code.



public class MainClass {
  public static void main(String[] args) {
    OuterLoop: for (int i = 2;; i++) {
      for (int j = 2; j < i; j++) {
        if (i % j == 0) {
          continue OuterLoop;
        }
      }
      System.out.println(i);
      if (i == 37) {
        break OuterLoop;
      }
    }
  }
}



2
3
5
7
11
13
17
19
23
29
31
37


Using the break Statement in a Loop: break out from a loop

public class MainClass {
  public static void main(String[] args) {
    int count = 50;
    for (int j = 1; j < count; j++) {
      if (count % j == 0) {
        System.out.println("Breaking!!");
        break;
      }
    }
  }
}



Breaking!!