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
}
}
OUTPUTbefore = 1
after = 1
before = 2
after = 2
before = 3
after = 3
before = 4
after = 4
before = 5
after = 5
before = 6
for loop completed.
DESCRIPTIONThe 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
- 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).