[HD Pg 174, Sec. 7.7.2 - rules-for-labeled-break-and-continue]

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
enthunoob
Posts: 60
Joined: Thu Apr 15, 2021 12:21 pm
Contact:

[HD Pg 174, Sec. 7.7.2 - rules-for-labeled-break-and-continue]

Post by enthunoob »

What confuses me is that if there are two loops within each other and inside the inner loop a continue or break statement with the name of the outer loop is called, then it jumps to the outer loop label and it still remembers the iteration values of the inner loop.

I would expect that jumping to the (label of the) code above, it just starts executing code from there and when it reaches the inner loop (again) it just starts with the initialization part of that inner loop. But it doesn't.

public static void doIt(int h){ int x = 1;
LOOP1 : do{
//when execution comes here from jumping to the LOOP1 label below (fe with input values h=5 and iteration values x =3 and y=4) when it goes to the next line of code, y is not reinitialized to 1 because the initialization part of the inner loop is (somehow) skipped.
LOOP2 : for(int y = 1; y < h; y++ ) {
if( y == x ) continue;
if( x*x + y*y == h*h){ System.out.println("Found "+x+" "+y);
break LOOP1;
} } x++;
}while(x<h);
}

What I learned in this chapter is that a label always marks a block of code. So 'local variables' of a labeled block of code, such as iteration values, are stored/memorized as long as that block did not finish completely. Just like local methods are kept in memory as long as that method did not finish entirely.


Please let me know if I understand correctly. And if so, I think it would be worth mentioning in this chapter.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: [HD Pg 174, Sec. 7.7.2 - rules-for-labeled-break-and-continue]

Post by admin »

>What confuses me is that if there are two loops within each other and inside the inner loop a continue or break statement with the name of the outer loop is called, then it jumps to the outer loop label and it still remembers the iteration values of the inner loop.

No, it doesn't.

>I would expect that jumping to the (label of the) code above, it just starts executing code from there and when it reaches the inner loop (again) it just starts with the initialization part of that inner loop. But it doesn't.

That is exactly what it does.

You are doing something wrong.
If you like our products and services, please help us by posting your review here.

enthunoob
Posts: 60
Joined: Thu Apr 15, 2021 12:21 pm
Contact:

Re: [HD Pg 174, Sec. 7.7.2 - rules-for-labeled-break-and-continue]

Post by enthunoob »

Thanks, I was.

Post Reply

Who is online

Users browsing this forum: No registered users and 47 guests