• Terminating the loop

    Loops can be terminated using the break and continue statement. If your program already do what you wnat, you may want to exit the loop to continue your program and also to save processing time. Terminating the loop is advisable rather than waiting for your loop to finish.

    The break Statement

    Break statement will cause the loop to exit and terminate and continue reading the codes after the loop. For example,

    int findMe = 5;
    for(int i=0; i<10; i++){
         if(i==findMe) {
              System.out.println("I've found it!");
              break;
         }
    }

    In the above example, there is a for loop that will continue to execute until such time that the variable i is equal to findMe variable. The loop will start from i=0  and end with i=5 and exit the loop because a break statement is written, thus, it will not continue from i=6 to i=10. Therefore, it will save processing time.

    The continue Statement

    The continue statement will cause the preceding codes not to be executed and will continue the loop for the next iteration. Consider the example below:

    for(int i=0; i<10; i++){
         if(i==5){
              continue;   
         }
         System.out.println("The value of i is: "+i);
    }

    In the above example, inside the for loop, we have set a condition that if variable i is equal to 5, we continue the for loop and skips the preceding codes. Therefore, if i is equal to 5, the continue statement will be executed, thus, it will skip the System.out. method and will just proceed to incremental definition and continue the loop. The program output will be:

    The value of i is: 0;
    The value of i is: 1;
    The value of i is: 2;
    The value of i is: 3;
    The value of i is: 4;
    The value of i is: 6;//5 will not be printed because of continue statement.
    The value of i is: 7;
    The value of i is: 8;

    Related Post