"break" Statements

This section describes 'break' statement, which is a branching statement that transfers the control to the end of the immediate enclosing 'switch', 'while', 'do', or 'for' statement.

"break" statements have 2 forms: non-labeled "break" statements and labeled "break" statements. Let's look at non-labeled "break" statements in this tutorial first.

What Is Non-Labeled "break" Statement? - A non-labeled "break" statement is a branching statement that transfers the control to the end of the immediate enclosing "switch", "while", "do", or "for" statement.

Here is the syntax for a non-labeled "break" statement.

```switch|while|do|for ... {
...
break
...
}
// break continues here
```

Note that non-labeled "break" statements can not be used in statements other than "switch", "while", "do", or "for" statements.

Here is a sample program that shows you how to use non-labeled "break" statements:

```/* BreakStatementTest.java
*/
class BreakStatementTest {
public static void main(String[] arg) {
java.io.PrintStream out = System.out;
int max = 20;

out.println("\"break\" statement in a single-level loop:");
int sum = 0;
int i = 1;
while (true) { // loop level 1
if (i > max ) break;
sum += i;
i++;
} // break continues here
out.println("   Sum of 1 to 20: "+sum);

boolean isPrime;
i = 3;
out.println("\"break\" statement in a multi-level loop:");
while (i < max) { // loop level 1
isPrime = true;
int j = 2;

while (j < i) { // loop level 2
isPrime = i%j > 0;
if (!isPrime) break;
j++;
} // break continues here

if (isPrime) out.println("   "+i+" is a prime number.");
i++;
}
}
}
```

If you compile and run the above program, you will see:

```herong> java BreakStatementTest.java

"break" statement in a single-level loop:
Sum of 1 to 20: 210

"break" statement in a multi-level loop:
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
19 is a prime number.
```