Question about com.enthuware.jfcja.v8.2.292

Oracle Certified Foundations Associate Java Certification Questions and Discussion
1Z0-811

Moderator: admin

Post Reply
james82abn
Posts: 1
Joined: Wed Jul 19, 2023 6:02 pm
Contact:

Question about com.enthuware.jfcja.v8.2.292

Post by james82abn »

For a nested loop with a break in its innermost loop, I am confused about the initialization. From the answer to this question and answer, it appears that the innermost loops (j, k) re-initialize to zero rather than maintain the iteration it had prior to the break. Is there a source where this situation (why the inner loops are re-initialized after a break) is explained.

Code: Select all

class LoopTest
{
	public static void main(String [] args)
	{
		int counter = 0;
		outer: for(int i = 0; i < 3; i++) 
			    for(int j = 0; j < 3; j++)
				for(int k = 0; k < 3; k++)
				{
					if(k - j > 0) break middle;
					counter++;
				}
		System.out.println(counter);
	}
}
Last edited by admin on Thu Jul 20, 2023 10:13 am, edited 1 time in total.
Reason: Please put code inside [code] [/code]

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

Re: Question about com.enthuware.jfcja.v8.2.292

Post by admin »

Well, a break statement "breaks" the loop. Meaning, the loop condition and the increment section of the for loop are not executed and the control is transferred immediately to the statement that appears immediately after the closing brace of the for loop. Everything regarding the loop (i.e. the loop variable etc.) is forgotten. In other words, this loop goes out of scope. This is the general concept behind the break statement.

Now, if the for loop is nested inside another loop, then the next statement after the loop is the remaining code of the outer loop. Thus, the iteration of the outer loop will continue and if the next iteration of the outer loop is executed, then the inner loop will also be executed afresh. Therefore, the loop variables of the inner loop will be reinitialized. There is no knowledge of the previous execution of the inner loop.

I am not sure what kind of reason are you looking for but this is how loops have been designed to work. Code inside a loop is executed afresh upon each iteration.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: Katzor and 117 guests