Java jump statement

Source: Internet
Author: User
Tags terminates

JAVA supports three jump statements:Break, continue, and return. These statements transfer control to other parts of the program. Next we will discuss each statement.


Note: apart from the jump statements discussed here,Java also supports another method that can change the execution process of your program:Exception Handling. Exception Handling provides a structured method that allows your program to capture and handle runtime errors. It is controlled by the following five keywords:Try, catch, throw, throws, and finally. Essentially,Exception Handling Mechanism allows your program to complete a non-local branch jump. As exception handling is a big topic, we will discuss it in detail.

5.3.1 Use the break statement
In Java, the break statement has three functions. First, you can see that in the switch statement, it is used to terminate a statement sequence. Second, it can be used to exit a loop. Third, it can be used as an "advanced" GOTO statement. The last two usage methods are described below.

Use break to exit the loop

You can use the break statement to forcibly exit the loop and ignore any other statements in the loop body and the conditional test of the loop. When a break statement is encountered in a loop, the loop is terminated, and the program controls the statement after the loop to start again. The following is a simple example:

// Using break to exit a loop.
Class breakloop {
Public static void main (string ARGs []) {
For (INT I = 0; I <100; I ++ ){
If (I = 10) break; // terminate loop if I is 10
System. Out. println ("I:" + I );
}
System. Out. println ("Loop complete .");
}
}

This program generates the following output:

I: 0
I: 1
I: 2
I: 3
I: 4
I: 5
I: 6
I: 7
I: 8
I: 9
Loop complete.

As you can see, although the for loop is designed to run from 0 to 99, when I is equal to 10, the break statement terminates the program. Break statements can be used in any Java loop, Including Infinite loops intentionally set. For example, rewrite the previous program with a while loop as follows. The output of this program is the same as that seen just now.

// Using break to exit a while loop.
Class breakloop2 {
Public static void main (string ARGs []) {
Int I = 0;
While (I <100 ){
If (I = 10) break; // terminate loop if I is 10
System. Out. println ("I:" + I );
I ++;
}
System. Out. println ("Loop complete .");
}
}

When a break statement is used in a series of nested loops, it only terminates the innermost loop. For example:

// Using break with nested loops.
Class breakloop3 {
Public static void main (string ARGs []) {
For (INT I = 0; I <3; I ++ ){
System. Out. Print ("pass" + I + ":");
For (Int J = 0; j <100; j ++ ){
If (j = 10) break; // terminate loop if J is 10
System. Out. Print (J + "");
}
System. Out. println ();
}
System. Out. println ("loops complete .");
}
}

This program generates the following output:

Pass 0: 0 1 2 3 4 5 6 7 8 9
Pass 1: 0 1 2 3 4 5 6 7 8 9
Pass 2: 0 1 2 3 4 5 6 7 8 9
Loops complete.

It can be seen that the break statement in the internal loop only terminates this loop, and the External Loop is not affected.

For break, remember two points here. First, there can be more than one break statement in a loop. But be careful that too many break statements will destroy your code structure. Second, the break in the switch statement only affects the switch statement, without affecting any loops.

Note: Break is not designed to provide a normal method for loop termination. The Condition Statement of a loop is used to terminate the loop. The break statement is used to cancel a loop only in special circumstances.

Use break as a form of GOTO

In addition to switch statements and loops, a break statement can also be used as a "civilized" form of a GOTO statement. Java does not have a GOTO statement, because the GOTO statement provides an unstructured way to change the program running process. This usually makes the program difficult to understand and maintain. It also blocks the optimization of Some compilers. However, in some cases, the GOTO statement is useful and valid for constructing process control. For example, when you exit from a nested deep loop, the GOTO statement is very helpful. Therefore, Java defines an extension form of the break statement to handle this situation. By using break in this form, you can terminate one or several code blocks. These code blocks do not have to be a loop or a part of a switch statement. They can be any block. In addition, because this form of break statement has labels, you can specify where to re-start the execution. You will see that break brings you the benefit of Goto and does not give up the trouble caused by the GOTO statement.

The common format of the label break statement is as follows:

Breaklabel;
Here, the label Label is the label that identifies the code block. When this form of break is executed, the control is passed out of the specified code block. The code block to be tagged must enclose the break statement, but it does not need to directly enclose the break block. This means that you can use a tagged break statement to exit a series of nested blocks. However, you cannot use a break statement to pass control to a code block that does not contain a break statement.

To specify a code block, add a label at the beginning. A label can be a valid Java identifier followed by a colon. Once you add a label to a block, you can use this label as the break statement object. This will re-start the execution at the end of the tagged block. For example, the following program shows three nested blocks, each of which has its own tag. The break statement enables the execution to jump forward. Two println () statements are skipped after the end of the code block defined as second.

// Using break as a civilized form of Goto.
Class break {
Public static void main (string ARGs []) {
Boolean T = true;
First :{
Second :{
Third :{
System. Out. println ("before the break .");
If (t) Break second; // break out of second block
System. Out. println ("This won't execute ");
}

System. Out. println ("This won 'texecute ");
}
System. Out. println ("this is after secondblock .");

}
}
}

Run the program to generate the following output:

Before the break.
This is after second block.

One of the most common usage of the label break statement is to exit the nested loop. For example, in the following program, the outer loop is executed only once:

// Using break to exit from nested loops
Class breakloop4 {
Public static void main (string ARGs []) {
Outer:
For (INT I = 0; I <3; I ++ ){
System. Out. Print ("pass" + I + ":");
For (Int J = 0; j <100; j ++ ){
If (j = 10) Break outer; // exit both loops
System. Out. Print (J + "");
}
System. Out. println ("This will notprint ");
}
System. Out. println ("loops complete .");
}
}
This program generates the following output:

Pass 0: 0 1 2 3 4 5 6 7 8 9 loops complete.

As you can see, when the internal loop returns to the External Loop, both cycles are terminated. Remember, if a tag is not defined in the block surrounded by break, you cannot break it. For example, the following program is invalid and will not be compiled:

// This program contains an error.
Class breakerr {
Public static void main (string ARGs []) {
One:
For (INT I = 0; I <3; I ++ ){
System. Out. Print ("pass" + I + ":");
}
For (Int J = 0; j <100; j ++ ){
If (j = 10) break one; // wrong
System. Out. Print (J + "");
}
}
}

Because the cycle labeled one does not enclose the break statement, the control cannot be passed to this block.

5.3.2 use the continue statement
Sometimes it is useful to force a loop to be repeated early. That is, you may want to continue running the loop, but ignore the statement that repeats the remaining loop body. In fact, Goto only skips the loop body and reaches the end of the loop. The continue statement is a supplement to the break statement. In the while and do while loops,The continue statement transfers the control directly to the conditional expression of the control loop, and then continues the loop process.In a for loop, the repeated expression of the loop is evaluated, then the conditional expression is executed, and the loop continues to be executed. For these three loops, any intermediate code will be bypassed.

The following example uses the continue statement to print two numbers in each line:

// Demonstrate continue.
Class continue {
Public static void main (string ARGs []) {
For (INT I = 0; I <10; I ++ ){
System. Out. Print (I + "");
If (I % 2 = 0) continue;
System. Out. println ("");
}
}
}

This program uses the % (Modulo) operator to check whether variable I is an even number. If yes, the loop continues to run without outputting a new line. The result of this program is as follows:

0 1
2 3
4 5
6 7
8 9

For a break statement, continue can specify a tag to indicate which loop to continue. The following example uses the continue statement to print a triangle multiplication table ranging from 0 to 9:

// Using continue with a label.

Class continuelabel {

Public static void main (string ARGs []) {

Outer:
For (INT I = 0; I <10; I ++ ){

For (Int J = 0; j <10; j ++ ){

If (j> I ){
System. Out. println ();
Continue outer;
}

System. Out. Print ("" + (I * j ));
}
}

System. Out. println ();

}

}

In this example, the continue statement terminates the cycle of counting J and continues the next cycle of counting I. The output of this program is as follows:

0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81

Very good use of the continue statement is rare, one reason is that Java provides a series of rich loop statements that can be applied to the vast majority of applications. However, for special cases that require early repetition, the continue statement provides a structured method for implementation.

5.3.3Return Statement
The last control statement is return. The return statement is used to explicitly return data from a method. That is,The Return Statement allows the program to control the return to the method to call it.Therefore, it is classified as a jump statement. Here we will give a brief introduction to it.

At any time of a method, the return statement can be used to make the branch program being executed return to the method that calls it. 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.

// Demonstrate return.
Class return {
Public static void main (string ARGs []) {
Boolean T = true;
System. Out. println ("before thereturn .");
If (t) return; // return to caller
System. Out. println ("This won 'texecute .");
}
}

The result of this program is 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 unreachable code error because the compiler knows that the final println () Statement will never be executed. To prevent this error, we use the if statement to "cheat" the compiler for this example.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.