Java Control Loop Statement Break,continue,return__java

Source: Internet
Author: User

The Java language does not provide a goto statement to control the jump, which improves the readability of program flow control, but reduces the flexibility of programmatic controls. To compensate for this deficiency, Java provides continue and break to control the loop structure, and in addition, return can end the entire method and end a loop.

One. Use break end loop

1. Forcibly terminate a loop when a condition arises, used to completely end a loop, and jump out of the loop body.

eg

for (int i=0;i<10;i++) {

if (i==2) {

No more execution of i=3 .... Jump straight out of the loop

Break

}

}

2.break not only can end the loop, you can also directly end its outer loop, you need to immediately follow a tag after the break, which is used to represent an outer loop, the label is followed by the following: identifier. Labels are useful only if they are placed before a loop statement

eg

Outer

for (int j=0;i<5;j++) {

for (int i=0;i<3;i++) {

if (i==1) {

Jump out of the loop identified by the outer label

Break outer;

}

}

}
Two. Use continue to ignore the remaining statements in this cycle

1.eg:

for (int i=0;i<10;i++) {

if (i==2) {

I equals 2 o'clock, will not execute the statement below, enter i=3 continue to execute

Continue

}

System.out.println ("hello!");

2. Similar to a break, continue can also be used with a label to skip the remaining statements of the second loop of the loop that is identified by the label

Three. Use return End method

The 1.return is not a keyword used specifically for loop structure control, but is used to end a method that ends when a method executes to a return statement, and the loop naturally ends. Unlike Break,continue, return closes the entire method directly, regardless of the number of loops within it.


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.