Using labeled break as a Form of Goto

break statement gives you the benefits of a goto. The general form of the labeled break statement is shown here:


break label;

To name a block, put a label at the start of it.

A label is any valid Java identifier followed by a colon.
The following code demonstrates the labeled block and labeled break:
 
public class Main {
  public static void main(String args[]) {
    boolean t = true;
    first: {
      second: {
        third: {
          System.out.println("Before the break.");
          if (t)
            break second; // break out of second block
          System.out.println("This won't execute");
        }
        System.out.println("This won't execute");
      }
      System.out.println("This is after second block.");
    }
  }
}

Running this program generates the following output:


Before the break.
This is after second block.

The following code uses a labeled break statement to exit from nested loops.

public class Main {
  public static void main(String args[]) {
    outer: for (int i = 0; i < 3; i++) {
      System.out.print("Pass " + i + ": ");
      for (int j = 0; j < 100; j++) {
        if (j == 10)
          break outer; // exit both loops
        System.out.print(j + " ");
      }

      System.out.println("This will not print");
    }
    System.out.println("Loops complete.");

  }
}  

This program generates the following output:


Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

You cannot break to any label which is not defined for an enclosing block. For example, the following program is invalid and will not compile:

  
public class Main {
  public static void main(String args[]) {
    one: for (int i = 0; i < 3; i++) {
      ;
    }
    for (int j = 0; j < 100; j++) {
      if (j == 10)
        break one; // WRONG
    }
  }
}

If you try to compile the program, it will generate the following error message.


D:\>javac Main.java
Main.java:8: undefined label: one
        break one; // WRONG
        ^
1 error
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.