Here is a question from KamExam Question Bank : public class KamFor { public static void main(String argv[]){ int i; int j; outer: for (i=1;i <3;i++) inner: for(j=1; j<3; j++) { if (j==2) continue outer; System.out.println("Value for i=" + i + " Value for j=" +j); } } } 1) Value for i=1 value for j=1 2) Value for i=2 value for j=1 3) Value for i=2 value for j=2 4) Value for i=3 value for j=1 What is the output and how did u get it ? . Please explain step by step . Tushar Matkar
Hello Tushar, its nice to see ur problem on javaranch. as u know that the command given is continue it will break the current iteration and continue with the next iteration. as continue is written as "continue outer" so it will search for the loop which has "outer :". and continue for the next iteration till the loop returns true. as in the example u will i<3 and j<3 so one thing is clear that i and j will never have a value three. hence 4 option is discarded. then the condition of if which is "if(j==2) continue outer" says that if the value of j is 2 break the current itertion and continue with the next iteration of loop having "outer " which is the loop having i. from this we can say that value j=2 will never be printed as s.o.p is after the continue outer and the programme will never rich that line if j is 2. hence option 3 is also discarded. so finally we can that from above that i=1,2 and j=1 are the only valid values which will be printed hence option 1 and 2 are the right answer. iteation wise the value will be for iteration 1 :- i=1 j=1 so the value will be printed 2 :- i=1 j=2 this will not be printed as continue outer will execute and it will force to stop the inner loop and then increment the value of i by 1. 3 :- i=2 j=1 so the value will be printed 4 :- i=2 j=2 this will not be printed as continue outer will execute and it will force to stop the inner loop and then increment the value of i by 1. then i will be 3 but as condition is that i<3 it will beark the loop and come out of it.