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