The difference between break, return and continue (Java)

1. break is used to completely end a loop and jump out of the loop body.

No matter what kind of loop, once a break is encountered in the loop body, the system will completely end the loop and start executing the code after the loop.

class Demo3 {
    public static void main(String[] args) {
       
    for(int i=1;i<=5;i++){       
      if(i==4){
        break;
    }
    }
    System.out.println("Java");
}
}

Break can not only end its cycle, but also its outer cycle. In this case, you need to follow the break with a label, which is used to identify an outer loop. A label in Java is an identifier followed by an English colon (:). And it must be placed before the loop statement to work.

public class Demo4{
    public static void main(String[]args){
    
    outer:
    for(int i=0;i<4;i++){
        
        for(int j=0;j<3;j++){
            System.out.println("i The value is:"+i+"   j The value is:"+j);
            if(j==1){
                break outer;
            }
        }
        
    }
    }
}

2. Return is not specifically used to jump out of a loop. The function of return is to end a method.

Once a return statement is executed inside the loop, the return statement will end the method and the loop will naturally end.

Unlike continue and break, return directly ends the entire method, no matter how many levels of loops the return is in.

Code 1:

class Demo3 {
    public static void main(String[] args) {
       
    for(int i=1;i<=5;i++){       
      if(i==4){
        //break;
        return;
    }
    }
    System.out.println("Java");
}
}

Code two:

public class Demo6
{
    public static void main(String[]args){
        for(int i=0;i<3;i++){
            System.out.println("i The value is:"+i);
            if(i==1){
               return;
            }
        System.out.println("continue After that");
            }
    }
}

3. The function of continue is similar to break. The difference is that continue just stops this cycle and then starts the next cycle. Break is to stop the cycle completely.

public class Demo5
{
    public static void main(String[]args){
        for(int i=0;i<3;i++){
            System.out.println("i The value is:"+i);
        if(i==1){
           continue;
        }
        System.out.println("continue After that");
            }
    }
}

Tags: Java

Posted on Tue, 03 Dec 2019 15:19:59 -0800 by kof20012