Page 87 - TP_iPlus_V2.1_Class8
P. 87

For example:

                 public class BreakStatement
                 {

                    public static void main(String args[])
                     {
                           int i;

                               for(i=1; i<=10; i++)
                               {

                                      if(i==5)
                                      {
                                             break;
                                                                                                    Output
                                      }
                                      else
                                      {
                                             System.out.println("The value of i is: " + i);

                                      }
                               }
                               System.out.println("Loop is terminated");

                     }
                 }
                 In the preceding program, the for loop terminates when the value of the variable i becomes 5.
                 This is because the break statement gets executed when the condition given with the ‘if’ keyword
                 becomes true (i == 5), which causes the loop to stop executing and come outside the loop.

                 The continue statement

                 Unlike the break statement, the continue statement forces the next iteration of the loop to take
                 place and skips the current iteration.
                 For example:

                 public class ContinueStatement
                 {

                    public static void main(String args[])
                     {
                           int i;

                               for(i=1; i<=10; i++)
                               {
                                      if(i==5)

                                      {
                                             System.out.println("Loop is continued"); continue;


                                                                                                                  85
                                                                 Conditional, Looping and Jump Statements in Java
   82   83   84   85   86   87   88   89   90   91   92