You can use the break statement to exit the loop directly, ignoring any other statements in the loop body and testing the cycle conditions. When a break statement is encountered in a loop, the loop is terminated,ProgramThe statement after the loop starts again. For example, if the for loop is designed to run from 0 to 99 and then output the numbers 0 to 99, But when I is equal to 10, the break statement terminates the program. Therefore, the program only outputs 0 to 10. When a break statement is used in a series of nested loops, it only terminates the innermost loop.
While continue stops executing the current repetition, and then returns the loop start and start the new repetition. Continue is used to skip some statements in the loop body, that is, not to execute these statements.
The return statement is used to explicitly return data from a method. That is, the Return Statement enables the program to control the return to call its method. Therefore, it is classified as a jump statement. Although the return statement is detailed at the beginning of chapter 7th, we will briefly introduce it here. At any time of a method, the return statement can be used to make the branch program being executed return to call its method. The following example illustrates this. In the following example, because the Java running system calls main (), the Return Statement returns the program execution to the Java running system. Source: exam Major
// Demonstrate return. Class
Return {
Public static void main (string ARGs []) {
Boolean T = true;
System. Out. println ("before the return .");
If (t) return;
// Return to caller
System. Out. println ("This won't execute .");
}
}
The program results are as follows:
Before the return.
As you can see, the last println () statement is not executed. Once the return statement is executed, the program control is passed to its caller.
Last point: in the above program, the IF (t) statement is necessary. Without it, the Java compiler will mark "the execution fails.Code"(Unreachable code) error because the compiler knows that the last println () Statement will never be executed. To prevent this error, we can execute it for this example. Here we use the if statement to "cheat" the compiler.