Menu
Topics Index
...
`


Control Statements > Jump Statements >
Siva Nookala - 06 Oct 2016
By using break, you can force immediate termination of a loop even though there are iterations to be completed.

e.g., In the following program which prints numbers from 1 to 15 can be terminated, without completing the 15 iterations by using a break statement.
Break for loop
class BreakForLoop
{
    public static void main(String arg[])
    {
        for(int i = 1; i <= 15; i++)
        {
            System.out.println("before = " + i ); // LINE A
        
            if(i == 6) break;  // LINE B
        
            System.out.println("after = " + i );  // LINE C
        }
        System.out.println("for loop completed."); // LINE D
    
    }
}
OUTPUT

before = 1
after = 1
before = 2
after = 2
before = 3
after = 3
before = 4
after = 4
before = 5
after = 5
before = 6
for loop completed.

DESCRIPTION

The for loop iterates from 1 to 15 and prints the number i before the break and after the break statement. When the value of i is 6 then the break statement is called, which terminates (or stops) the for loop. That is why no number greater than 6 is printed, although i can go upto to 15. Also note that when the break statement is called, the code below that break statement will not be executed and goes directly to the next statement after the for loop. i.e. LINE C is not executed, but LINE D. Hence before = 6 is printed but not after = 6. Also for loop completed is printed since LINE D which is after the for loop is executed.

THINGS TO TRY
  • Check the output for the below code.
    for (int i = 0; i < 5; i++)
    {
        System.out.println("value of i : " + i);
        break;
    }
    The output of the above code will be just value of i : 0, since break is executed after first iteration.
  • Try for the below code.
    int i = 1;
    while (i < 5)
    {
        System.out.println("value of i : " + i);
        break;
    }
    The output of the above code is value of i : 1, since break is executed after the first iteration.
  • Try using break statement in switch and do-while.
  • break can also be used inside while loop.
  • break can also be used inside nested loops (loop inside loop).

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.