Friday, 30 May 2014

Break Statement in Java

Break Statement

In java , the break statement has three uses.
1. It terminates a statements sequence in switch statement.
2. It can be used to exit a loop.
3. It can be used as a "civilized" form of goto.

And last two uses are explained here.

2. Using the break to exit loop:

By break  , you can force to terminates the loop.When a break statement is encountered inside a loop , 
the loop is terminated and program control reeches to the next statement to the loop.The break statement can be used with any of the loop.

Simple program of Break statement:

package org.modi;
public class Test
{
  public static void main(String[] args)
  {
 int i=1;
 while(i<100)
 {
  if(i==5)
  {
   break; //terminates the loop while i become 5
  }
  System.out.println("i : "+i);
  i++;
 }
 System.out.println("After while loop");
 }
}
OUTPUT
i : 1
i : 2
i : 3
i : 4
After while loop
You can see in above program the while loop designed  to iterate from 1 to 99 ,
But the break statement terminate the loop while i reach to 5
When break statement  used inside a set of nested loops , it will only break out the innermost loop.

3. Using break as a goto form:

Java does not have a goto statement,so where goto is required java defines the expanded form of the break statement.
By using this form of the break statement you can break out one or more blocks of code.
This form of the break works with a label.

The general form of the labeled break statement is :

break label;
Here,label is the name of a label that identifies the block of the code.When this form of the break executes , control transferred 
to the named block.
To name a block , put label at the start of it.A label is valid java identifier followed by a colon (:) .

Simple program of break statement in from of goto:

package org.modi;
public class Test
{
   public static void main(String[] args)
   {
       one:
       {
          two:
         {
             three:
            {
              System.out.println("Block Three begin");
              if(true)
                  break two;  //control goes out of block two
              System.out.println("Block Three End");
           }
           System.out.println("Block Two");
        }
        System.out.println("Block one");
      }
   }
 
}
OUTPUT
Block Three begin
Block one

0 comments :

Post a Comment