1
0

Break Statement in Java

The break statement has two forms: labeled and unlabeled. You say the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break statement to terminate a for, while, or do-while loop, as shown in the following BreakDemo program:

Program to demonstrate the break statement:

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. The control flow then transfers to the print statement at the end of the program.

The above program output is:

Found 12 at index 4

The unlashed break statement terminates the loop in which it is executed and transfers the control to the statement immediately following the body of the loop. The other form of break statement is discussed with the labeled loop in the next section.

Leave a Reply