aspose file tools*
The moose likes Beginning Java and the fly likes Label??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Label???" Watch "Label???" New topic


Mark Henryson
Ranch Hand

Joined: Jul 11, 2005
Posts: 200

a. Prints: 0
b. Prints: 1
c. Prints: 2
d. Prints: 3
e. Compilation Error.

I got the above program from one book. Why we are using lab1 and lab2. What is the use? And also what will be the output the above program. I thought 0. But it gives 2 as answer. How?
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
causes the code to break out of the loop that is labelled lab1 (i.e. the outer loop). If the break had not had the label, it would have only broken out of the inner loop (the one labelled lab2. With the code as it stands, the lab2 label on the inner loop is unnecessary.

Manuel Moons
Ranch Hand

Joined: Mar 05, 2002
Posts: 229
First of all let me say that this piece of code is terrible. If I ever encounter someone in real life that writes code like this I will punch his lights out

No seriously, using the (de)incrementor in such a way is asking for trouble.

Anyways what happens is this:

You start out with j=2. When the lab1 rule is encountered for the first time. j=2 and i=1 at the time of the test so it succeeds. When the test is done the j value is upped by 1 so it's value becomes 3.

So in the lab2 rules at the time of the test the j=3, i=1 and k=0. So k < j and the test succeeds. j is reduced by one before continuing.
So when the j>k/i is executed it actually equals to this 2>0/1.
So the test passes and the lab1 loop is exited.

Resulting in a j == 2 value.

I hope you can follow me?
[ August 12, 2005: Message edited by: Manuel Moons ]
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
The first time the code reaches the line if (j > k/i), j = 2, k = 0 and i = 1, so the if statement is true (2 > 0/1), so the break is executed and it breaks out of both loops and executes the print statement.
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
Please ignore my last reply. Manuel is right, I missed the increments in the loop tests.
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
GOTO has long been considered a harmful operation however that masks the fact that it's also indispensible when you absolutely positively have to break out of several nested loops. Heaven forbid they make GOTO clear and concise but this would have been better than using continue/break with the label IMO. Labels are GOTO targets.

A pig by any other name would still smell. Billy Shakespeare, New Jersey.

[ August 12, 2005: Message edited by: Rick O'Shay ]
I agree. Here's the link:
subject: Label???