| Author |
doubt in continue and break
|
Divya Gehlot
Ranch Hand
Joined: Sep 10, 2006
Posts: 238
|
|
1) Compile time error, System.out has no print method 2) No output at runtime 3) Output of 0 4) Compile error, break cannot occur after its target label I expected the output to be 01 but when I run the above program got the ouput 0 . Can anybody explain me ?
|
SCJP1.5(81%)<br />SCDJWS(94%)<br />next mission SCEA(but need to wait or that)
|
 |
Nik Arora
Ranch Hand
Joined: Apr 26, 2007
Posts: 652
|
|
Hi divya, When i is 0 it comes in the loop and checks for both the condition what you have written since both condition returns false it goes to next line and prints 0. Now i is 1 so the second condition satisfies that is if(i>0), in the if block you have written a continue statement now control goes back to the for loop. i value gets incremented now its value is 2 so the condition fails that is i<2 and control comes out of the for loop. So only 0 gets printed. Regards Nik
|
 |
nitin pokhriyal
Ranch Hand
Joined: May 19, 2005
Posts: 263
|
|
if(har==ham){ //never gets here because they are not equal if(i > 0){ continue collar; } System.out.print(i); first time condition is false . so it will print 0. In second iteration i>0 condition will true and so it will go continue statement and loop will move to next iteration and then for loop condition will never be true for i after that so no SOP will be printed after first time
|
 |
Divya Gehlot
Ranch Hand
Joined: Sep 10, 2006
Posts: 238
|
|
thanks a alot. I got it
|
 |
Manfred Klug
Ranch Hand
Joined: Jun 04, 2007
Posts: 377
|
|
Hi, somebody interested in a small variation of the program? 1) Compile time error, System.out has no print method 2) No output at runtime 3) Output of 0 4) Compile error, break cannot occur after its target label
|
 |
Ketul Shah
Greenhorn
Joined: Jun 17, 2007
Posts: 2
|
|
code: public class HarHam{ public static void main(String argv[]){ HarHam hh = new HarHam(); hh.go(); } public void go(){ String har = "har"; String ham = "har"; collar: for(int i=0; i < 2 ; i ++){ if(har==ham){ break collar; } if(i > 0){ continue collar; } System.out.print(i); } } } -------------------------------------- The answer for this is "No Output at runtime".
|
 |
suresh koutam
Ranch Hand
Joined: Dec 29, 2004
Posts: 30
|
|
yep no output at runtime... the first condition is met and the break takes it out of the for loop.. Suresh Koutam
|
SCJP aspirant<br />SCWCD aspirant
|
 |
 |
|
|
subject: doubt in continue and break
|
|
|