permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes If construct? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "If construct?" Watch "If construct?" New topic
Author

If construct?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
The output of the foll code is
Ans : It'll print numbers from 0 to 4
The code is as follows :

Can any one explain me how did they get this output and why?
(need Proper Explainations)
Sonir
[Code edited by Val. PLEASE USE THE CODE tags]
[This message has been edited by Valentin Crettaz (edited December 10, 2001).]
Peter Chirco
Greenhorn

Joined: Nov 20, 2001
Posts: 4
void crazyLoop() {int c = 0;JACK: while (c < 8) {JILL: System.out.println(c);if (c > 3) break JACK; else c++;}}
Sonir
Here is what I think is happening:
Your first loop is Jack, which runs from c=0 to c=7. Your second loop is Jill, which stops Jack when c > 3 (the first time that happens is when c = 4). Since the print statement happens before the break statement, all values of c will be printed out, including the first value that will make the test in Jill false. Then we break out of Jack, and move on.
Pete
Kelley Koszegi
Greenhorn

Joined: Aug 20, 2001
Posts: 27
Hi Peter & Sonir,
Actually there is only one loop. The second 'loop' is just a print statement within the Jack loop. Note that in this case you would get the same behavior without the labels:
int c=0;
while (c < 8) {<br /> System.out.println(c);<br /> if (c > 3)
break;
else
c++;
}
So like Peter said, c will never be greater than 4. As soon as it is, the if statement is true and the loop is broken. No further increments or iterations are completed.
Also note that the 'Jill' label is useless.
Hope that is helpful,
--Kelley
Originally posted by Peter Chirco:
Here is what I think is happening:
Your first loop is Jack, which runs from c=0 to c=7. Your second loop is Jill, which stops Jack when c > 3 (the first time that happens is when c = 4). Since the print statement happens before the break statement, all values of c will be printed out, including the first value that will make the test in Jill false. Then we break out of Jack, and move on.
Pete[/B]


Kelley Koszegi<br />Sun Certified Java Programmer
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: If construct?