Java Tutorial/Statement Control/Break Statement
Содержание
Breaking Indefinite Loops
<source lang="java">
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; } } }
}</source>
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.
<source lang="java">
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); }
}</source>
The break Statement
- The break statement is used to break from an enclosing do, while, for, or switch statement.
- It is a compile error to use break anywhere else.
- "break" breaks the loop without executing the rest of the statements in the block.
For example, consider the following code
<source lang="java">
public class MainClass {
public static void main(String[] args) { int i = 0; while (true) { System.out.println(i); i++; if (i > 3) { break; } } }
}</source>
The result is
0 1 2 3
The Labeled break Statement
- The break statement can be followed by a label.
- The presence of a label will transfer control to the start of the code identified by the label.
- For example, consider this code.
<source lang="java">
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; } } }
}</source>
2 3 5 7 11 13 17 19 23 29 31 37
Using the break Statement in a Loop: break out from a loop
<source lang="java">
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; } } }
}</source>
Breaking!!