In: Computer Science
Which of this method of class String is used to obtain a length of String object?
What is the output of the below Java program with WHILE, BREAK and CONTINUE?
int cnt=0;
while(true)
{
if(cnt > 4)
break;
if(cnt==0)
{
cnt++;
continue;
}
System.out.print(cnt + ",");
cnt++;
}
1,2,3,4 |
||
Compiler error |
||
0,1,2,3,4, |
||
1,2,3,4, |
Step1:
First of We should be clear with break,continue,and while statements:
while: while is used to iterate again and again over the statements till the condition is true
break: break is used to break the loop and comes out from the loop without executing the remaining statements .
continue: Using this statements curser will jump to start of the loop without executing the remaining statements.
Step2:
Now Given code is:
int cnt=0;
while(true)
{
if(cnt > 4)
break;
if(cnt==0)
{
cnt++;
continue;
}
System.out.print(cnt + ",");
cnt++;
}
Step3:
Here cnt is 0 initially
while will try to execute infinitely because true is passed as condition which will always be true
Now here one if condition is there which will break the loop:
if(cnt > 4)
break;
It means when cnt value will gets greater then 4 it will comes out of the loop .
Now we have one more condition is there
if(cnt==0)
{
cnt++;
continue;
}
it will run only when cnt is equal to zero it means it will execute first time and increment cnt by 1 and jump to the start of the loop
After that we have
System.out.print(cnt + ",");
cnt++;
it will print cnt and a comma ( , )
so Code execution will go like this ..
firstly cnt is 0 so it will come inside second if condition and gets increment by 1 and jump to start of the loop without printing .
next time cnt will be 1 so it will not go in any if condition and 1, will gets printed similarly 2,3,4, gets printed in subsquent iteration .
Now when cnt will be equal to 5 it will gets into the first if condiion and break statements gets executed so it will comes out of the loop .
Output:
so final Output will be 1,2,3,4,
Please note that there will be a , at last of the output.
So third option is correct
Thanks