Differentiate between break and continue statements in java.
Answers
Answered by
4
Break statement takes the compiler out of the loop when it encounters it. Continue statement makes the compiler skip one iteration when it encounters it.
for(int i=1;i<=5;i++)
{
System.out.println(i) ;
if(i==3)
break;
}
Here the compiler will come out when i becomes 3.
for(int j=1;j<=5;j++)
{
if(j==3)
continue;
System.out.println(j) ;
}
Here, when j becomes 3, the compiler will skip the rest of the loop, become 4 and carry on with the upcoming iterations.
for(int i=1;i<=5;i++)
{
System.out.println(i) ;
if(i==3)
break;
}
Here the compiler will come out when i becomes 3.
for(int j=1;j<=5;j++)
{
if(j==3)
continue;
System.out.println(j) ;
}
Here, when j becomes 3, the compiler will skip the rest of the loop, become 4 and carry on with the upcoming iterations.
Pranjal01:
Kk. Thanks.
Answered by
4
Break statement
It is used to terminate unconditionally from small enclosing a like for,while, do...while, switch case etc
Eg;
Class BrainlyB
{void print ()
{for(int i = 1; i,<= 10;i++)
{System.out.prinntln(”$”);
if (i>2)
{break;}}}}
Output
First iteration
i=1
$
i>2 False
Next iteration
i=2
$
i>2 False
Next iteration
i=3
$
i>2 True
So the control comes out of the loop.
Continue statement
Eg:
Class BrainlyL
{void print ()
{for (int i=1;i<4;i++)
{System.out.println(i)
if (i%2==0)
{continue;}
System.out.println(i)}}}
Output
First iteration
i=1
1
1%2== 0 false
1
Next iteration
I=2
2
2%2==0 True
(2 does not get printed and next iteration is done)
Next iteration
i=3
3
3%2==0 False
3
The text condition is false so control comes out of the loop.
It is used to terminate unconditionally from small enclosing a like for,while, do...while, switch case etc
Eg;
Class BrainlyB
{void print ()
{for(int i = 1; i,<= 10;i++)
{System.out.prinntln(”$”);
if (i>2)
{break;}}}}
Output
First iteration
i=1
$
i>2 False
Next iteration
i=2
$
i>2 False
Next iteration
i=3
$
i>2 True
So the control comes out of the loop.
Continue statement
Eg:
Class BrainlyL
{void print ()
{for (int i=1;i<4;i++)
{System.out.println(i)
if (i%2==0)
{continue;}
System.out.println(i)}}}
Output
First iteration
i=1
1
1%2== 0 false
1
Next iteration
I=2
2
2%2==0 True
(2 does not get printed and next iteration is done)
Next iteration
i=3
3
3%2==0 False
3
The text condition is false so control comes out of the loop.
Similar questions