|
| INTERMEDIATE |
The syntax of a break statement is very simple:
break;
The break statement has two separate and distinct uses: exiting
a loop, and exiting a switch
statement. You cannot use a break anywhere but inside a loop
or a switch statement.
Within any kind of a loop, break causes
the loop to exit.
There is very little point in having a "bare" break
that unconditionally exits a loop. Almost always, the break is
embedded in an if statement. For example:
for (int i = 0; i < myArray.length; i++) { if (myArray[i] < 0) { System.out.println("Bad value in location " + i); break; } }
In the case of nested loops, break exits the innermost loop.
Use of the break statement is discouraged. Basically, this is
because it allows you to exit the loop in more than one way (the normal exit,
plus any conditions that cause a break), which can be confusing;
and it means that you may have to write additional code, after the loop, to
figure out what the loop did. Hence, before you break out of a
loop, you should try to find another way to get the same results.
break
after each block of code, execution flows into the next block. For example:
switch (grade) { case 'A': System.out.println("You did great!"); break; case 'B': case 'C': case 'D': System.out.println("You passed."); case 'F': System.out.println("You flunked!"); }
In the above code,
grade is equal to 'A', Java prints "You
did great!" and the switch statement exits.grade is equal to 'F', Java prints "You
flunked!" and the switch statement exits.grade is equal to 'B', 'C', or
'D', Java prints "You passed.", because
the 'B' case flows into the 'C' case, which flows
into the 'D' case. However, in these three cases it also
prints "You flunked!", because there is no break
to prevent the 'D' case from flowing into the 'F'
case.The requirement for break statements within a switch
statement is widely regarded as poor language design, but it is consistent with
C and many other older languages.
| ADVANCED |
You can exit multiple levels of loops and/or switch statements by using labels.