Goto Statement in Java


The break statement may assign itself to provide a civilized form of the Goto statement. Java does not have any goto statement because this usually makes goto-ridden code hard to understand and hard to maintain.

However, there are a few places where valuable and legitimate construction for it to flow control. For example, Goto can be effective when you are exiting a set of deeply nested loops. To handle such situations, Java defines an extended form of a break statement. Using this broken form you can break one or more blocks of code for example. These blocks should not be part of any loop or switch. These can be any block. Further, you can specify where the execution will start again because break this form works with a label. As you can see, the break gives you the benefit of the doubt without any problems.

The general form of the labeled break statement is shown here :

break label;

Label with break statement

Program
public class Main
{
  public static void main (String[]args)
  {
      outer:
      for(int i=0;i<6;i++)
      {
          for(int j=0;j<6;j++)
          {
              if(j==5)
              {
                  break outer;
              }
              System.out.println("j = "+j);
          }
      }
  }
}
Run

In the example above, a label called "outer" is used. There is a nested loop inside it. Now if "j == 5" is inside the nested loop then "outer" will be interrupted which means execution of the whole loop will be stopped.


Label with continue statement

The following example shows a program of continuing statements labeled. If you do not know how to continue the statement, see the next tutorial.

Program
public class Main
{
  public static void main (String[]args)
  {
      first:
      for(int i=0;i<6;i++)
      {
          for(int j=0;j<6;j++)
          {
              if(j==1)
              {
                  continue first;
              }
              System.out.println("j = "+j);
          }
      }
  }
}
Run

In the example above, a label called "First" is taken and a nested loop is taken. Then if the condition is "j == 1" then the whole loop will continue from the beginning.