Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6985557

java - nuts and bolts - Break statement example

XMLWordPrintable

    • b08
    • generic
    • generic
    • Verified

      http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

      After the BreakDemo class in the discussion of the results:

      class BreakDemo {
          public static void main(String[] args) {

              int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
                                    2000, 8, 622, 127 };
              int searchfor = 12;

              int i;
              boolean foundIt = false;

              for (i = 0; i < arrayOfInts.length; i++) {
                  if (arrayOfInts[i] == searchfor) {
                      foundIt = true;
                      break;
                  }
              }

              if (foundIt) {
                  System.out.println("Found " + searchfor
                                     + " at index " + i);
              } else {
                  System.out.println(searchfor
                                     + " not in the array");
              }
          }
      }

      This program searches for the number 12 in an array. The break statement, shown in boldface, terminates the for loop when that value is found. Control flow then transfers to the print statement at the end of the program. This program's output is:
      Found 12 at index 4

      "Control flow then transfers to the print statement at the end of the program." This statement is incorrect here because control flow is transferred to the if-then Statement (to then determine which message should be printed).

            skannan Sowmya Kannan (Inactive)
            skannan Sowmya Kannan (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: