Search code examples
javalabelkeywordbreakcontinue

Explain about java continue & break the following code briefly


Explain briefly the function of the code below. About continue & break operations. I can't understand properly label1, label2.....Please describe code functions (The label is basically used in nested loops  But note that they are used here to understand the labelling process)

class example {
    public static void main(String args[]) {
        int i = 0;
        int j = 0;
        label1: while (i++ < 5) {
            label2: for (;;) {
                label3: do {
                    System.out.print(i + " " + j + " ");
                    switch (i + j++) {
                    case 0:
                        continue label3;
                    case 1:
                        continue label2;
                    case 2:
                        continue label1;
                    case 3:
                        break;
                    case 4:
                        break label3;
                    case 5:
                        break label2;
                    case 6:
                        break label1;
                    default:
                        break label1;
                    }
                } while (++j < 5);
            }
        }
    }
}

Solution

  • The following line first checks if 0 < 5 and then increases the value of i to 1:

    while (i++ < 5)
    

    Thus the following statement prints 1 0 as the value of i is now 1 and that of j is 0:

    System.out.print(i + " " + j + " ");
    

    As a result of the two above mentioned processings, the following line is evaluated as switch (1 + 0) and then the value of j is increased to 1:

    switch (i + j++)
    

    As a result of the above mentioned processing, case (1) becomes true and therefore the control goes to label2 and again falls back to the following statement which prints 1 1:

    System.out.print(i + " " + j + " ");
    

    Now, the following line is evaluated as switch (1 + 1) and then the value of j is increased to 2:

    switch (i + j++)
    

    As a result of the above-mentioned processing, case (2) becomes true and therefore the control goes to label1 from where it falls to the following line which first checks if 1 < 5 and then increases the value of i to 2:

    while (i++ < 5)
    

    Then it goes to the following statement which prints 2 2 as the value of i is now 2 and that of j is 2:

    System.out.print(i + " " + j + " ");
    

    And so on...

    I hope, it is clear to you. Apart from this, I also recommend you follow Java naming convention e.g. class example should be class Example as per the naming convention.

    Feel free to comment in case of any doubt/issue.