Java break statement - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Sunday, November 4, 2018

Java break statement

Break statement in Java

Java break statement has three uses:

  1. It can use to exit a loop.
  2. it can be used as a "civilized" form of goto i.e label
  3. It terminates a statement sequence in switch statement.

Using break to exit a loop

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop.

Example:

/ Using break to exit from a loop
public class BreakForLoop {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      System.out.println("Value of i= " + i);
      if (i == 5) {
        break;
      }
    }
    System.out.println("Outside the for loop.");
  }
}

Output:

Value of i= 0
Value of i= 1
Value of i= 2
Value of i= 3
Value of i= 4
Value of i= 5
Outside the for loop.

As you can see the output, although the for loop is designed to run from 0 to 9, the break statement caused it to terminate early, when i equals to 5.

Java break statement can be used with any Java's loops, including intentionally infinite loops.

Java break statement with do-while loop

Example:

// break statement with do-while loop
public class BreakDoWhileLoop {
  public static void main(String[] args) {
    int i = 0;
    do {
      System.out.println("Value of i= " + i);

      if (i == 5) break;

    } while (++i < 10);

    System.out.println("Outside the do-while loop.");
  }
}

Output:

Value of i= 0
Value of i= 1
Value of i= 2
Value of i= 3
Value of i= 4
Value of i= 5
Outside the do-while loop.

Java break statement with while loop

Example:

// break statement with while loop
public class BreakWhileLoop {
  public static void main(String[] args) {
    int i = 0;
    while (i < 10) {
      System.out.println("Value of i= " + i);

      if (i == 5) break;
      i++;
    }

    System.out.println("Outside the while loop.");
  }
}

Output:

Value of i= 0
Value of i= 1
Value of i= 2
Value of i= 3
Value of i= 4
Value of i= 5
Outside the while loop.

Java break statement inside nested loop

Java break statement will only break out from the innermost loop, when it is used inside a set of nested loops.

Example:

// demonstrate break statement with nested loop
// break statement break out from the innermost loop.
public class BreakInnerMostLoop {

  public static void main(String[] args) {
    // Outer loop
    for (int i = 0; i < 10; i++) {
      System.out.println("Outer loop: i= " + i);

      // Inner loop
      for (int j = 0; j < 10; j++) {
        System.out.println(" Inner loop: j= " + j);
        if (j == 2) break; // break out from the inner loop
      }
    }
  }
}

Output:

Outer loop: i= 0
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 1
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 2
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 3
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 4
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 5
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 6
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 7
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 8
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2
Outer loop: i= 9
 Inner loop: j= 0
 Inner loop: j= 1
 Inner loop: j= 2

Using break as a form of goto (label)

Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. This usually makes goto-ridden code hard to understand and hard to maintain. It also prohibits certain compiler optimizations.

The goto can be useful when you are exiting from a deeply nested set of loops. Java provides labeled break statement to achieve it. Using this form of the break statement, you can break out of one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any block.

Syntax:

break label;

abel is the name of a label that identifies a block of code.

The labeled block must enclose the break statement, but it does not need to be the immediately enclosing block.

Example:

Using labeled break statement with if block.

// Using break as a civilized form of goto.
class BreakBlocksOfCode {
  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");
        } // end of third label
        System.out.println("This won't execute");
      } // end of second label
      System.out.println("This is after second block.");
    } // end of first label
    System.out.println("This is after first block.");
  }
}

Output:

Before the break.
This is after second block.
This is after first block.

Java break statement with labeled for loop

Mostly labeled break statement is used to break out from nested for loop.

Example:

// Using break to exit from nested loops
class BreakNestedLoop {
  public static void main(String args[]) {

    outer:
    for (int i = 0; i < 3; i++) {
      System.out.print("Pass " + i + ": ");

      for (int j = 0; j < 10; j++) {
        if (j == 5) break outer; // exit both loops
        System.out.print(j + " ");
      } // end of inner loop

      System.out.println("This will not print");
    } // end of outer label loop

    System.out.println("Loops complete.");
  }
}

Output:

Pass 0: 0 1 2 3 4 Loops complete.

Keep in mind that you cannot break to any label which is not defined for an enclosing block.

Example:

// This program contains an error.
class BreakErr {
  public static void main(String args[]) {
    one:
    for (int i = 0; i < 3; i++) {
      System.out.print("Pass " + i + ": ");
    }

    for (int j = 0; j < 100; j++) {
      if (j == 10) break one; // compile time error
      System.out.print(j + " ");
    }
  }
}

Compile give error like java: undefined label: one

Since the loop labeled one does not enclose the break statement, it is not possible to transfer control out of that block

Java break Statement with Switch

The break that terminates a switch statement affects only that switch statement and not any enclosing loops.

Example:

public class ForLoopWithSwitch {
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
      System.out.println("Value of i= " + i);

      switch (i) {
        case 0:
          System.out.println("Zero");
          break;
        case 1:
          System.out.println("One");
          break;
        case 2:
          System.out.println("Two");
          break;
        case 3:
          System.out.println("Three");
          break;
        case 4:
          System.out.println("Four");
          break;
        default:
          System.out.println("Values is not between 1 to 4.");
      }
    }
  }
}

Output:

Value of i= 0
Zero
Value of i= 1
One
Value of i= 2
Two
Value of i= 3
Three
Value of i= 4
Four

To understand the example of the break with the switch statement, please visit here: Java Switch Statement.

1 comment :

  1. factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
    eehhaaa This newsletter from Jaalifestyle: As we all know, we need a total of 1.5 million people to start an advertising program.
    sniffies Sniffies isn’t bookmarked on my phone, however I’ve been logged in enough that the web target will auto-complete on my personal browser.
    college-party-guide One of the most important rituals for students in college is to throw the most memorable student dorm celebration.

    ReplyDelete