Break and Continue in Java

Source: Internet
Author: User

When using a looping statement, the loop will only jump out if the expression for the loop condition is false. Sometimes we want to jump out of the loop early, then we need to use break or continue inside the loop.

Break can terminate loops and switch statements. A non-marking break transfers control to the next bar of the current (most internal) loop (while,do....while,for or switch), and if there is a label, it is transferred to the statement with that label. For example:

1  PackageCom.review.chapter2;2 3  Public classTestbreak {4      Public Static voidMain (string[] args) {5         inti = 0;6         7One while(I < 5) {//defines a while loop with a label8System.out.println ("outer:" +i);9i++;Ten             if(i = = 3){ OneSystem.out.println ("Inner:" +i); A                  BreakOne//when I=3, jump out of the loop labeled One -             } -         } the          -System.out.println ("Looping with labels"); -     } -}

In the above code, we define a while loop with a label, and in the IF statement, when i==3, it jumps out of the loop labeled one and proceeds to the following statement. So the results are as follows:

   

The continue statement without a label indicates that the remaining statement to be executed by the loop is skipped, and then the next loop is started. For example, let's print out the odd sum of the 1--100:

1  PackageCom.review.chapter2;2 3  Public classOddsum {4      Public Static voidMain (string[] args) {5         intsum = 0;6         7          for(inti = 1;i < 100;i++){8             if(i% 2 = = 0){9                 Continue;Ten             } OneSum + =i; A         } -          -System.out.println ("1--100 Odd and": "+sum); the     } -}

A labeled continue usage is similar to a labeled break statement. This is not to be discussed here.

Break and Continue in Java

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.