Witscale Test Center

5.4 Interrupting the loops


5.4 Interrupting the loops

The regular repetitive execution of the loops is usually terminated when the condition they specify becomes false. You can also abruptly terminate the execution of the loop by using one of the following statements:

The break statement

The return statement

A call to the exit() method of java.lang.System class. (System.exit(0))

When the loop encounters any of these three statements, the loop terminates abruptly and the control goes out of the loop. However, where exactly the control goes depends on which statement you have used in the loop.

When break is encountered within a loop, the execution jumps out of the loop and the first statement after the loop is executed. If return is used within a loop in a method, the execution jumps out of the loop and out of the method. The control is returned to the calling method. The call to System.exit(0)within a loop is a drastic measure. This call terminates the currently running JVM. It will cause not only the currently executing loop to terminate, but also the enclosing program.  There is one more statement continue which when used in loops stops the execution of a current iteration and directly moves to the next one. Let us look at the break and continue statements in the context of loops.