The break statement | Decision making, Branching and Looping

The break statement

1) Can only appear within a loop or a switch statement.

2) Causes an immediate exit from a loop structure before the test condition is met. Once a break statement is encountered, the loop immediately terminates, skipping any remaining code.

For example,
for (int x = 0; x < 10; x++)
{
if (x == 5)
break;
else
System.out.print(” ” + x);
}

will end prematurely when x takes on a value of 5.

The output displayed will be:
0 1 2 3 4

3) It may specify the label of the loop to be abandoned. This makes it possible to abandon a specific loop.

For example,

outer: for (int i = 1; i <= 5; i++)
{
for (int j = 5; j >= 1; j–) {
if (i == j)
break outer;
else
System.out.println(“i = ” + i + “, j = ” + j);
}
}

will end the outer loop when i equals j.

The output displayed will be:
i = 1, j = 5
i = 1, j = 4
i = 1, j = 3
i = 1, j = 2

4) It causes an immediate exit from a switch, skipping any remaining code.

For example, if key is a char variable having a value entered by the user, the following statements will display whether they entered an ‘A’ or a ‘B’:

switch (key)
{
case ‘a’:
case ‘A’:
System.out.println(“You entered an ‘A'”);
break;
case ‘b’:
case ‘B’:
System.out.println(“You entered a ‘B'”);
break;
default:
System.out.println(“You did not enter an ‘A’ or a ‘B'”);
break;
}