Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside.another. For example, here is a program that. nests for loops Java supports three jump statements: break, continue, and return. These statements transfer contralto another part of your program. Each is examined heu.
addition to the jump statements discussed here, Java supports one other that you nil Chang your program’s flow of execution: through exception handling. Exception handling provides a structured method by run-time errors can be trapped and “alleged by your program. It is supported by the catch throw, throw and finally. III essence, tile exception handling mechanism allows your program to I,reform a Ion local branch. Since exception is a large topic, it is discussed .
In Java, the break statement has three uses. First, as you have seen, it terminates a .
statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a “civilized” form of go to. The last two uses are explained here.
Using’ break to Exit a Loop
By using break, you can force immediate termination of a loop, buying the conditional expression and any remaining code in the body of the loop. When a break, statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here i,s a simple example:As you can see, although the for.loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i equals 10. The break statement can be used, with any of Java’s loops, including intentionally infinite loops. For example, here is the preceding program coded by use of while , loop. Tile output from this pr~gram is the, same as just shown.
As you can see, the break statement in the inner ‘loop only causes termination of that loop. The outer loop is unaffected. .’Here are two other points to remember about break. First, ‘more than one break statement appear in a loop. However, be careful. Too many break statements have the tendency to destructive your code. Second, the break that terminates a switch statement affects only that switch statement and not any enclosing.