Java's Jump Statements | Controls Statement | Java Programming | Java For Beginner | break...continue....return.

Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.

Using break

In Java, the break statement has two uses. First, as you have seen, it terminates a statement

sequence in a switch statement. Second, it can be used to exit a loop.

By using break, you can force immediate termination of a loop, bypassing the conditional

expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next

statement following the loop.


Here is a simple example:


class BreakLoop
{
   public static void main(String args[])
   {
     for(int i=0; i<100; i++)
     {
         if(i == 10) break; // terminate loop if i is 10
         System.out.println("i: " + i);
     }
     System.out.println("Loop complete.");
   }
}


Output

  i: 0
  i: 1
  i: 2
  i: 3
  i: 4
  i: 5
  i: 6
  i: 7
  i: 8
  i: 9
  Loop complete.



Note

Here are two other points to remember about break. First, more than one break statement may appear in a loop. However, be careful. Too many break statements have the tendency to destructure your code. Second, the break that terminates a switch statement affects only that switch statement and not any enclosing loops.


Using continue


Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action.


Here is an example program that uses continue to cause two numbers to be printed on
each line:


// Demonstrate continue.

class Continue
{
   public static void main(String args[])
   {
      for(int i=0; i<10 br="" i="">       {
         System.out.print(i + " ");
         if (i%2 == 0) continue;
         System.out.println("");
     }
   }
}


Output

0 1
2 3
4 5
6 7
8 9



return

The last control statement is return. The return statement is used to explicitly return from
a method. That is, it causes program control to transfer back to the caller of the method.

As such, it is categorized as a jump statement.

At any time in a method the return statement can be used to cause execution to branch
back to the caller of the method. Thus, the return statement immediately terminates the

method in which it is executed. 


For Example:-


// Demonstrate return.

class Return
{
   public static void main(String args[])
   {
      boolean t = true;
      System.out.println("Before the return.");
      if(t) return; // return to caller
      System.out.println("This won't execute.");
   }
}



Output

Before the return.




Post a Comment

1 Comments