Java break Statement

In Java, the break statement has these three uses :

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

As we already discussed about the first uses, so here we only discuss about the last two uses.

Use break to Exit a Loop

By using keyword break, you can force quick termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. Once a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Below is a simple example, demonstrates break to exit a loop :

Example - Use break to Exit From a for Loop

Here is an example program, showing how to use break statement to exit from a for loop in Java:

/* Java Program Example - Java break Statement */
// Using break to exit a loop

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        for(int i=0; i<100; i++)
        {
            if(i == 10)
                break;
            System.out.println("i is " + i);
        }
        
        System.out.println("Loop complete.");
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java break to exit a loop

As you can see that the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i becomes 10.

The break statement can be used with any of Java's loops, including intentionally infinite loops. For example, here is the preceding program coded by the use of a while loop.

Example - Use break to Exit From a while Loop

Here is an example program, showing how to use break statement to exit from a while loop in Java:

/* Java Program Example - Java break Statement
*  Use break to exit a while loop */

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        int i = 0;
        
        while(i<100)
        {
            if(i == 10)
                break;
            System.out.println("i is " + i);
            i++;
        }
        
        System.out.println("Loop completed.");
        
    }
}

When the above program is compile and executed, it will produce the same output as above :

java use break to exit loop

Whenever used inside a set of nested loops, the break statement will only break out of the innermost loop. For example :

Example - Use break to Exit From nested Loop

Here is an example program, showing how to use break statement to exit from nested loop in Java:

/* Java Program Example - Java break Statement
*  Use break in nested loops */

public class JavaProgram
{   
    public static void main(String args[])
    {
        
        for(int i=0; i<3; i++)
        {
            System.out.print("Pass " + i + " : ");
            for(int j=0; j<100; j++)
            {
                if(j == 10)    // terminate loop
                    break;     // if j is 10
                
                System.out.print(j + "  ");
            }
            System.out.println();
        }
        
        System.out.println("Loops Completed.");
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java break keyword

As you can see that the break statement in the inner loop only causes the termination of that loop only. The outer loop is unaffected.

Here are the two other points to remember about the break :

Use break as a Form of Goto

In addition to its uses with switch and loops, the break statement can also be employed by itself to provide a "civilized" form of goto statement.

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

There are some places where goto is a important and legitimate construct for the flow control. For example, goto can be useful when you are exiting from deeply nested set of loops. To handle such situations, Java defines an expanded form of break statement. By using this form of break, you can, for example, break out of one or more blocks of code. These blocks need not be the part of the loop or a switch. They can be any block. Furthermore, you can specify precisely where the execution will resume, because this form of break works with a label. As you will see, the break gives you the benefits of a goto without its problems.

labeled break Syntax

Below is the general form of the labeled break statement :

break label;

Most often, label is the name of a label that identifies a block of code. It can be a standalone block of code but it can also be a block that is the target of another statement. When this type of break executes, control is transferred out of named block. The labeled block must enclose the break statement, but it does not necessitated to be immediately enclosing block. It means, for example, that you can use a labeled break to exit from a set of nested blocks. But you can't use the break to transfer the control out of a block that does not enclose the break statement.

To name any block, put a label at the start of it. A label is any legal Java identifier followed by a colon.

Once you have labeled any block, you can use this label as the target of a break statement. Doing so, causes an execution to resume at the end of the labeled block. For example, here this program shows the three nested blocks, each with its own label. The break causes the execution to jump forward, past the end of the block labeled second, skipping the two println().

/* Java Program Example - Java break Statement
*  Use break as a civilized form of goto */

public class JavaProgram
{   
    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 the second block.");
        }
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java break as goto

One of the most common uses of a labeled break statement is to exit from the nested loops.

For example, in this program, the outer loop executes only once :

/* Java Program Example - Java break Statement
*  Using break to exit from nested loops */

public class JavaProgram
{   
    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("\nLoops completed.");
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

java break to exit nested loops

As you can see here that when the inner loop breaks to the outer loop, both the loops have been terminated. Notice here that this example labels the for statement, which has a block of code as its target.

Always keep in mind that you can't break to any label which is not defined for an enclosing block.

More Examples

Here are some examples listed that uses break statement, you can go for.

Java Online Test


« Previous Tutorial Next Tutorial »