1. Function and difference
The purpose of break is to break out of the current loop block (for, while, do while) or program block (switch). The function in the loop block is to jump out of the loop body currently circulating. The role in the program block is to compare the interrupt and the next case condition.
Continue is used to end the execution of subsequent statements in the loop body and jump back to the beginning of the loop program block to execute the next loop, rather than immediately loop body.
2. Other uses
break and continue can be used with statement tags.
This is all very simple. Here is a comprehensive example and you will understand:
/** * Created by IntelliJ IDEA. * User: leizhimin * Date: 2007-11-29 * Time: 15:47:20 */ public class Test { public static void main(String args[]) { Test test = new Test (); test.testBreak1(); test.testContinue1(); test.testBreak2(); test.testContinue2(); } /** * Test continue * continue is used to end this loop*/ public void testContinue1() { System.out.println("------------------------"); for (int i = 1; i <= 5; i++) { if (i == 3) continue; System.out.println("i=" + i); } } /** * break is used to end the entire loop body*/ public void testBreak1() { System.out.println("-----------------------------"); for (int i = 1; i <= 5; i++) { if (i == 3) break; System.out.println("i=" + i); } } /** * Test break statements with labels* The tag can only be written before the loop body. By the way, learn the definition and use of statement tags in java*/ public void testBreak2() { System.out.println("--------------------------"); int i = 1; int k = 4; lable1: for (; i <= 5; i++, k--) { if (k == 0) break lable1; System.out.println("i=" + i + " ; k=" + k); } } public void testContinue2() { System.out.println("---------------------"); lable1: for (int i = 1; i < 10; i++) { lable2: System.out.println("i=" + i); for (int j = 0; j < 10; j++) { if (j == 9) continue lable1; } } } } Running results:
--------测试break1------- i=1 i=2 --------测试continue------- i=1 i=2 i=4 i=5 --------测试break2------- i=1 ; k=4 i=2 ; k=3 i=3 ; k=2 i=4 ; k=1 --------测试continue2------- i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 Process finished with exit code 0
The above is the summary of the use of break and continue keywords in Java brought to you by the editor. I hope everyone will support Wulin.com~