TestLoopLabel.java


import java.io.*;
public class TestLoopLabel {
   public static void main (String[] args) throws IOException {
      int n = 0;
      outer: 
      for (int i=0; i<5; i++){
         System.out.println("Out: i=" + i);
         middle: 
         for (int j=0; j<5; j++){
            System.out.println("  Middle: j=" + j);
            inner: 
            for (int k=0; k<5; k++){
               System.out.print("    inner: k=" + k + " n=" + (++n));
               if (k % 5 == 0){
                   System.out.println();
                                
                   // different choices here
                   // ----------------------
                                
                   //break mid; 
                   break outer;
                   //continue;
                   //continue out;         
               }
               System.out.println("    inner: something after");
             }
         }
      }
                         
      // break in a labeled block
      Block: 
      //int cc=3;//if you insert line, compiler err results
      {
         System.out.println("Before break!");
         long x = System.currentTimeMillis();
         // half the chance
         if (x % 2 == 1)
            break Block;
         System.out.println("After break!");
      }
                   
      int xx = 3;
      // break in a labeled if block
      iiff:
      if (xx == 3)
      {
         System.out.println("before break iiff");
         long x = System.currentTimeMillis();
         // half the chance
         if (x % 2 == 1)
            break iiff;
         System.out.println("after break iiff");
      }
      
      // Illegal using break w/o label
      //{
      //   long x = System.currentTimeMillis();
      //   if (x % 3 == 1)
      //      break;
      //   System.out.println("After break!");
      //}
                   
      // continue only allowed in loop
      //Block1: 
      //{
      //   long x = System.currentTimeMillis();
      //   if (x % 3 == 1)
      //      continue Block1;
      //   System.out.println("After continue!");
      //}
                   
      System.in.read();
   }
}

last updated: 10-06-1999
Copyright © 1999 - 2003 Roseanne Zhang, All Rights Reserved
[ Java certification page] [ SCJP FAQ] [ JavaChina]