Summary of usage of break and continue keywords in Java

  • 2020-05-17 05:26:20
  • OfStack

1. Roles and differences

break is used to break out of the current loop block (for, while, do while) or program block (switch). The action in the loop block is to jump out of the loop body that is currently being looped. The role in the block is to compare the interrupt to the next case condition.

continue is used to terminate the execution of subsequent statements in the loop body and to jump back to the beginning of the loop block to execute the next loop instead of the immediate loop body.

2. Other USES

break and continue can be used with statement labels.

This is all very simple, here is a comprehensive example to see it:


/** 
* 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 To close the loop  
   */ 
  public void testContinue1() { 
    System.out.println("-------- test continue-------"); 
    for (int i = 1; i <= 5; i++) { 
      if (i == 3) continue; 
      System.out.println("i=" + i); 
    } 
  } 

  /** 
   * break To close the whole loop  
   */ 
  public void testBreak1() { 
    System.out.println("-------- test break1-------"); 
    for (int i = 1; i <= 5; i++) { 
      if (i == 3) break; 
      System.out.println("i=" + i); 
    } 
  } 

  /** 
   *  Test with labels break statements  
   *  Tags can only be written before the body of the loop, by the way 1 Under the java The definition and use of statement labels in  
   */ 
  public void testBreak2() { 
    System.out.println("-------- test break2-------"); 
    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("-------- test continue2-------"); 
    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; 
      } 
    } 
  } 
}

Operation results:


-------- test break1------- 
i=1 
i=2 
-------- test continue------- 
i=1 
i=2 
i=4 
i=5 
-------- test break2------- 
i=1 ; k=4 
i=2 ; k=3 
i=3 ; k=2 
i=4 ; k=1 
-------- test 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 

Related articles: