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
}
}
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.
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.
for (int i = 0; i < 5; i++)
{
System.out.println("value of i : " + i);
break;
}
break
is executed after first iteration.int i = 1;
while (i < 5)
{
System.out.println("value of i : " + i);
break;
}
break
is executed after the first iteration.break
statement in switch
and do-while
.