Break, continue and return

11 0 0
                                    

break
    - two forms of break
        1. Labelled
        2. Unlabelled
    - the Unlabelled break is normally used in switch while the Labelled break is mostly used to get out in an outer loop coming from an inner loop.

================================

class TestLabelledBreak{
    public static void main(String[] args){
        String[] name = {
            {"La", "Le", "Li", "Lo", "Lu"},
            {"Ma", "Me", "Mi", "Mo", "Mu"}
        };

        loop1:
        for(int i=0; i<2; i++){
            for(int j=0; j=5; j++){
                if(name[i][j] = "Mi"){
                    break loop1;
                }
                System.out.print(name[i][j]);
            }
            System.out.println();
        }
    }
}

================================
Result:
LaLeLiLoLu
MaMe

continue
    - it is same as the break except it does not end the loop but just skips the loop and proceed to the next loop.
    - this has labelled and unlabelled forms too.

return
   - when your method has a return data type, you can use this return keyword followed by that value.

================================

class TestReturn{
    private int addNumbers(int x, int y){
       return x + y;
    }

    private void displayHello(){
       System.out.println("Hello");
       return;
    }

    public static void main(String[] args){
        int n = 4;
        int m = 8;
        TestReturn t = new TestReturn();
        int total = t.addNumbers(n, m);
        System.out.println(total);

        t.displayHello();
    }
}

================================
12
Hello

The first return returns an int type. The return is followed by adding two integers.
The second returns nothing. You can use a return with no value to exit the method.

Java ProgrammingWhere stories live. Discover now