Break Statement in Java


In Java, there are three uses of break statements.

  1. It ends a statement sequence in a switch statement.
  2. It Can be used to exit a loop.
  3. It can be used as a "civilized" form of goto.

Using break to Exit a loop

Using the break statement you can force the conditional expression on the condition of the loop and the instant termination of a loop by bypassing any remaining code. The loop ends when a break statement is encountered inside a loop, and control resumes in the next program of the loop. Here is a simple example:

Program
public class Main
{
  public static void main (String[]args)
  {
    for (int i = 1; i < 20; i++)
      {
	if (i == 5)
	  {
	    break;
	  }
	System.out.println ("i = " + i);
      }
    System.out.println ("Loop complete.");
  }
}
Run

As you can see, although the for loop is designed to run from 1 to 20, the break statement causes it to terminate early, when i equals 5.


The break statement can be used in any loop in Java, even in infinite loops. The break statement is shown below by a while loop.

Program
public class Main
{
  public static void main (String[]args)
  {
    int i=1;
    while(i<100)
    {
        if(i==10)
        {
            break;
        }
        System.out.println("i = "+i);
        ++i;
    }
    System.out.println("Loop complete");
  }
}
Run

When used within a group of nested loops, the break statement will only come out of the inner loop.

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

In the example above, the break statement terminates the inner loop but not the outer loop.


Note :
Here are two more things to keep in mind when it comes to break statements.

  1. Multiple break statements may be present in a loop. However, beware that many break statements can damage the structure of your code.
  2. A break statement that shuts down a switch statement only affects that switch statement and no other contagious loops.