In the process of learning Java language by yourself, it is easy to confuse the usage of break and continue. In order to facilitate quick review and review in the future, I will leave a study note here.
Brief description
In the main part of any iterative statement, break and continue can be used to control the flow of the loop. Among them, break is used to forcefully exit the loop and not execute the remaining statements in the loop. Continue stops executing the current iteration, and then returns to the beginning of the loop to start the next iteration.
Source code
The following program shows you an example of break and continue in for and while loops:
package com.mufeng.thefourthchapter;public class BreakAndContinue { public static void main(String[] args) { for (int i = 0; i < 100; i++) { if (i == 74) {// Out of for loop break; } if (i % 9 != 0) {// Next iteration continue; } System.out.print(i + " "); } System.out.println(); int i = 0; while (true) { i++; int j = i * 27; if (j == 1269) {// Out of loop break; } if (i % 10 != 0) {// Top of loop continue; } System.out.print(i + " "); } }} Output result
01.0 9 18 27 36 45 54 63 72
02.10 20 30 40
Source code parsing <br />In this for loop, the value of i will never reach 100, because once i reaches 74, the break statement will break the loop. Usually, break is only needed if you don't know when the interrupt condition is met. As long as i cannot be divisible by 9, the continue statement will return the execution process to the beginning of the loop (this increments the value of i). If divisible, the value will be displayed. The reason why the output result shows 0 is because 0%9 equals 0.
Finally, you can see a "infinite while loop". However, there is a break statement inside the loop that aborts the loop. In addition, you will also see that the execution sequence of the continue statement is moved back to the beginning of the loop without completing the content used after the continue statement. (The value is printed only if i can be divisible by 10.)
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.